轉自:
http://www.java265.com/JavaCourse/202204/2938.html
HttpClient是一個java語言撰寫的包,
我們使用HttpClient可以非常方便的發送Http請求
它使基于Http協議請求內容變得非常簡單
HttpClient是Apache Jakarta Common下的子專案 它里面封裝了很多使用http協議訪問的工具,可用于高效訪問http
下文筆者講述基于HttpClient Utils工具類撰寫一個檔案上傳的示例分享,如下所示:
HttpClient Utils進行表單進行檔案上傳的示例分享,如下所示
實作思路:
1.獲取連接
2.宣告一個HttpPost
3.創建上傳體FileBody
4.定義一個HttpEntity傳送檔案
5.execute執行上傳操作
6.獲取回傳資訊
7.關閉連接
/**
* 上傳檔案
*/
public void upload() {
CloseableHttpClient httpclient = HttpClients.createDefault();
try {
HttpPost httppost = new HttpPost("http://java265.com/uploadFile");
FileBody bin = new FileBody(new File("F:\\image\\sendpix0.jpg"));
StringBody comment = new StringBody("A binary file of some kind", ContentType.TEXT_PLAIN);
HttpEntity reqEntity = MultipartEntityBuilder.create().addPart("bin", bin).addPart("comment", comment).build();
httppost.setEntity(reqEntity);
System.out.println("executing request " + httppost.getRequestLine());
CloseableHttpResponse response = httpclient.execute(httppost);
try {
System.out.println("----------------------------------------");
System.out.println(response.getStatusLine());
HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
System.out.println("Response content length: " + resEntity.getContentLength());
}
EntityUtils.consume(resEntity);
} finally {
response.close();
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/500099.html
標籤:其他
上一篇:Python做一個英漢翻譯小字典
