废话不多说了,直接给大家贴关键代码了。
public static void httpPost(Activity activity,String urlstr,String uploadFile,String newName) {
LogUtil.info("getEhttpPostt", "urlstr="+urlstr+";uploadFile="+uploadFile+";newName="+newName,"i");
String end = "\r\n";
String twoHyphens = "--";
String boundary = "*****";//边界标识
int TIME_OUT = 10*1000; //超时时间
HttpURLConnection con = null;
DataOutputStream ds = null;
InputStream is = null;
try {
URL url = new URL(urlstr);
con = (HttpURLConnection) url.openConnection();
con.setReadTimeout(TIME_OUT);
con.setConnectTimeout(TIME_OUT);
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 = new DataOutputStream(con.getOutputStream());
ds.writeBytes(twoHyphens + boundary + end);
ds.writeBytes("Content-Disposition: form-data; "
+ "name=\"stblog\";filename=\"" + newName + "\"" + end);
ds.writeBytes(end);
// 取得文件的FileInputStream
FileInputStream fStream = new FileInputStream(uploadFile);
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
int length = -1;
while ((length = fStream.read(buffer)) != -1) {
ds.write(buffer, 0, length);
}
ds.writeBytes(end);
ds.writeBytes(twoHyphens + boundary + twoHyphens + end);//结束
fStream.close();
ds.flush();
is = con.getInputStream();
int ch;
StringBuffer b = new StringBuffer();
while ((ch = is.read()) != -1) {
b.append((char) ch);
}
showDialog(activity,true,uploadFile,"上传成功" + b.toString().trim());
} catch (Exception e) {
showDialog(activity,false,uploadFile,"上传失败" + e);
}finally {
if(ds!=null){
try {
ds.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (con != null) {
con.disconnect();
}
}
}
private static void showDialog(final Activity activity,final Boolean isSuccess,final String uploadFile,final String mess) {
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
new AlertDialog.Builder(activity).setTitle("Message")
.setMessage(mess)
.setNegativeButton("确定", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
File file = new File(uploadFile);
if(file.exists()&&isSuccess){//日志文件存在且上传日志成功
file.delete();
Toast.makeText(activity, "log日志已删除", Toast.LENGTH_SHORT).show();
}
}
}).show();
}
});
}
以上内容是小编给大家介绍的Android 通过httppost上传文本文件到服务器的实例代码,代码简单易懂,附有注释,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对编程网网站的支持!
您可能感兴趣的文章:Android 通过Base64上传图片到服务器实现实例android选择视频文件上传到后台服务器Android选择图片或拍照图片上传到服务器Android开发中调用系统相册上传图片到服务器OPPO等部分手机上出现短暂的显示桌面问题的解决方法Android实现上传文件到服务器实例详解Android使用post方式上传图片到服务器的方法Android程序开发通过HttpURLConnection上传文件到服务器Android异步上传图片到PHP服务器android 上传文件到服务器代码实例Android上传文件到服务器的方法