Android 通过httppost上传文本文件到服务器的实例代码
废话不多说了,直接给大家贴关键代码了。
/**
*往服务器上上传文本比如log日志
*@paramurlstr请求的url
*@paramuploadFilelog日志的路径
*/mnt/shell/emulated/0/LOG/LOG.log
*@paramnewNamelog日志的名字LOG.log
*@return
*/
publicstaticvoidhttpPost(Activityactivity,Stringurlstr,StringuploadFile,StringnewName){
LogUtil.info("getEhttpPostt","urlstr="+urlstr+";uploadFile="+uploadFile+";newName="+newName,"i");
Stringend="\r\n";
StringtwoHyphens="--";
Stringboundary="*****";//边界标识
intTIME_OUT=10*1000;//超时时间
HttpURLConnectioncon=null;
DataOutputStreamds=null;
InputStreamis=null;
try{
URLurl=newURL(urlstr);
con=(HttpURLConnection)url.openConnection();
con.setReadTimeout(TIME_OUT);
con.setConnectTimeout(TIME_OUT);
/*允许Input、Output,不使用Cache*/
con.setDoInput(true);
con.setDoOutput(true);
con.setUseCaches(false);
//设置http连接属性
con.setRequestMethod("POST");//请求方式
con.setRequestProperty("Connection","Keep-Alive");//在一次TCP连接中可以持续发送多份数据而不会断开连接
con.setRequestProperty("Charset","UTF-8");//设置编码
con.setRequestProperty("Content-Type",//multipart/form-data能上传文件的编码格式
"multipart/form-data;boundary="+boundary);
ds=newDataOutputStream(con.getOutputStream());
ds.writeBytes(twoHyphens+boundary+end);
ds.writeBytes("Content-Disposition:form-data;"
+"name=\"stblog\";filename=\""+newName+"\""+end);
ds.writeBytes(end);
//取得文件的FileInputStream
FileInputStreamfStream=newFileInputStream(uploadFile);
/*设置每次写入1024bytes*/
intbufferSize=1024;
byte[]buffer=newbyte[bufferSize];
intlength=-1;
/*从文件读取数据至缓冲区*/
while((length=fStream.read(buffer))!=-1){
/*将资料写入DataOutputStream中*/
ds.write(buffer,0,length);
}
ds.writeBytes(end);
ds.writeBytes(twoHyphens+boundary+twoHyphens+end);//结束
fStream.close();
ds.flush();
/*取得Response内容*/
is=con.getInputStream();
intch;
StringBufferb=newStringBuffer();
while((ch=is.read())!=-1){
b.append((char)ch);
}
/*将Response显示于Dialog*/
showDialog(activity,true,uploadFile,"上传成功"+b.toString().trim());
}catch(Exceptione){
showDialog(activity,false,uploadFile,"上传失败"+e);
}finally{
/*关闭DataOutputStream*/
if(ds!=null){
try{
ds.close();
}catch(IOExceptione){
e.printStackTrace();
}
}
if(is!=null){
try{
is.close();
}catch(IOExceptione){
e.printStackTrace();
}
}
if(con!=null){
con.disconnect();
}
}
}
/*显示Dialog的method*/
privatestaticvoidshowDialog(finalActivityactivity,finalBooleanisSuccess,finalStringuploadFile,finalStringmess){
activity.runOnUiThread(newRunnable(){
@Override
publicvoidrun(){
newAlertDialog.Builder(activity).setTitle("Message")
.setMessage(mess)
.setNegativeButton("确定",newDialogInterface.OnClickListener(){
publicvoidonClick(DialogInterfacedialog,intwhich){
Filefile=newFile(uploadFile);
if(file.exists()&&isSuccess){//日志文件存在且上传日志成功
file.delete();
Toast.makeText(activity,"log日志已删除",Toast.LENGTH_SHORT).show();
}
}
}).show();
}
});
}
以上内容是小编给大家介绍的Android通过httppost上传文本文件到服务器的实例代码,代码简单易懂,附有注释,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对毛票票网站的支持!