首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

java使用http去服务器上传文件(图片)

2013-10-06 
java使用http往服务器上传文件(图片)使用http往服务端上传文件,要使用MultipartEntity,需要引入httpmime包

java使用http往服务器上传文件(图片)
使用http往服务端上传文件,要使用MultipartEntity,需要引入httpmime包,在附件中。


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; }

热点排行