httpclient 如何传字节
展开全部
public String post(String pathToOurFile,String urlServer) throws ClientProtocolException, IOException {
HttpClient httpclient = new DefaultHttpClient();
//String pathToOurFile = "abc.txt"; //uploadfile
//String urlServer = "http://192.168.1.2/upload.action";
HttpPost httppost = new HttpPost(urlServer);
File file = new File(pathToOurFile);
MultipartEntity mpEntity = new MultipartEntity(); //文件传输
ContentBody cbFile = new FileBody(file);
mpEntity.addPart("userfile", cbFile); // <input type="file" name="userfile" /> 对应的
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 responseStr=EntityUtils.toString(resEntity,"utf-8");
System.out.println(resEntity );
resEntity.consumeContent();
httpclient.getConnectionManager().shutdown();
return responseStr;
}
HttpClient httpclient = new DefaultHttpClient();
//String pathToOurFile = "abc.txt"; //uploadfile
//String urlServer = "http://192.168.1.2/upload.action";
HttpPost httppost = new HttpPost(urlServer);
File file = new File(pathToOurFile);
MultipartEntity mpEntity = new MultipartEntity(); //文件传输
ContentBody cbFile = new FileBody(file);
mpEntity.addPart("userfile", cbFile); // <input type="file" name="userfile" /> 对应的
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 responseStr=EntityUtils.toString(resEntity,"utf-8");
System.out.println(resEntity );
resEntity.consumeContent();
httpclient.getConnectionManager().shutdown();
return responseStr;
}
本回答被提问者和网友采纳
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询