使用http往
服务端上传文件,要使用MultipartEntity,需要引入httpmime包,在附件中。
class="java">public static String postFile(String uploadFile, final String uploadType, String userId) throws ClientProtocolException, IOException, JSONException {
HttpClient httpclient = new DefaultHttpClient();
//设置通信协议版本
httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
Log.i("chopin", uploadFile);
HttpPost httppost = new HttpPost(Const.ImageUpload);
File file = new File(uploadFile);
MultipartEntity mpEntity = new MultipartEntity(); //文件传输
ContentBody cbFile = new FileBody(file);
mpEntity.addPart("file", cbFile);
mpEntity.addPart("userId",new StringBody(userId));
mpEntity.addPart("uploadType",new StringBody(uploadType));
httppost.setEntity(mpEntity);
System.out.println("executing request " + httppost.getRequestLine());
HttpResponse response = httpclient.execute(httppost);
HttpEntity resEntity = response.getEntity();
System.out.println(response.getStatusLine());//通信Ok
String json="";
String path="";
if (resEntity != null) {
json=EntityUtils.toString(resEntity,"utf-8");
Log.i("chopin", json);
JSONObject p=null;
try{
p=new JSONObject(json);
path=(String) p.get("path");
}catch(Exception e){
e.printStackTrace();
}
}
if (resEntity != null) {
resEntity.consumeContent();
}
httpclient.getConnectionManager().shutdown();
return path;
}
- httpmime-4.1.1.jar (26.3 KB)
- 下载次数: 0