HttpClient--傳送請求
Maven依賴:
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
</dependency>
// 頭資訊
Map<String, String> head = new HashMap<String, String>();
head.put("accept", "*/*");
head.put("connection", "Keep-Alive");
head.put("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
head.put("Content-Type", "application/json");
1 get請求
/**
* 執行GET請求
*
* @param url
* @param param
* @return
*/
public static String doGet(String url, Map<String, String> param) {
CloseableHttpClient httpclient = HttpClients.createDefault();
String resultString = "";
CloseableHttpResponse response = null;
try {
// 建立uri
URIBuilder builder = new URIBuilder(url);
if (param != null) {
for (String key : param.keySet()) {
builder.addParameter(key, param.get(key));
}
}
URI uri = builder.build();
HttpGet httpGet = new HttpGet(uri);
response = httpclient.execute(httpGet);// 執行請求
// 判斷返回狀態是否為200
if (response.getStatusLine().getStatusCode() == 200) {
resultString = EntityUtils.toString(response.getEntity(),
"UTF-8");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (response != null) {
response.close();
}
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return resultString;
}
2 POST請求
/**
* POST傳遞form表單資料
*
* @param url
* @param param
* @return
*/
public static String doPostForm(String url, Map<String, String> param) {
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = null;
String resultString = "";
try {
HttpPost httpPost = new HttpPost(url);
// 建立引數列表
if (param != null) {
List<NameValuePair> paramList = new ArrayList<NameValuePair>();
for (String key : param.keySet()) {
paramList.add(new BasicNameValuePair(key, param.get(key)));
}
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(
paramList);
httpPost.setEntity(entity);
}
response = httpClient.execute(httpPost);// 執行http請求
resultString = EntityUtils.toString(response.getEntity(), "utf-8");
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return resultString;
}
3 POST傳送JSON資料
/**
* 傳送JSON資料
*
* @param url
* @param json
* @return
*/
public static String doPostJson(String url, String json) {
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = null;
String resultString = "";
try {
HttpPost httpPost = new HttpPost(url);
StringEntity entity = new StringEntity(json,
ContentType.APPLICATION_JSON);// 建立請求內容
httpPost.setEntity(entity);
response = httpClient.execute(httpPost);// 執行http請求
resultString = EntityUtils.toString(response.getEntity(), "utf-8");
} catch (Exception e) {
e.printStackTrace();
} finally {
// 關閉
try {
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return resultString;
}
4 傳送XML資料
public static String doPostXml(String url, String xmlData) {
logger.info("XML資料:"+xmlData);
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = null;
String resultString = "";
try {
HttpPost httpPost = new HttpPost(url);
// 資料
httpPost.addHeader("Content-Type","text/xml;charset=UTF-8");
StringEntity entity = new StringEntity(xmlData, "UTF-8");// 建立請求內容
httpPost.setEntity(entity);
// 執行http請求
response = httpClient.execute(httpPost);
resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return resultString;
}
Java傳送Form表單
新增Form表單,包括檔案
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
<version>4.5.2</version>
</dependency>
public static String doSubmitFormIncludeFile(String url,Map<String,Object> params,File file) throws ClientProtocolException, IOException {
CloseableHttpClient httpclient = HttpClients.createDefault();
try {
HttpPost httppost = new HttpPost(url);
//檔案
FileBody bin = new FileBody(file);
MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
MultipartEntityBuilder build = entityBuilder.addPart("file", bin);
//引數
Iterator<Entry<String, Object>> mapIterator = params.entrySet().iterator();
while(mapIterator.hasNext()) {
Entry<String, Object> next = mapIterator.next();
StringBody contentBody=new StringBody(next.getValue()+"",ContentType.MULTIPART_FORM_DATA);
build.addPart(next.getKey(), contentBody);
}
HttpEntity reqEntity = build.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());
}
String resultString = EntityUtils.toString(response.getEntity(), "utf-8");
EntityUtils.consume(resEntity);
System.out.println(resultString);
return resultString;
} finally {
response.close();
}
} finally {
httpclient.close();
}
}
測試
String url = "http://127.0.0.1:8084/cloudai/task/uploadFile";
Map<String,Object> params=new HashMap<>();
params.put("a", 1);
params.put("b", 2);
File file=new File("D:\\a.xls");
String doForm = doSubmitFormIncludeFile(url, params, file);
System.out.println(doForm);
@PostMapping("/uploadFile")
public Object uploadFile(@RequestParam Map<String,Object> params,@RequestParam("file") MultipartFile multipartFile){
return params;
}
參考:
https://blog.csdn.net/u010826617/article/details/80236226
https://blog.csdn.net/wsdtq123/article/details/78888734
https://blog.csdn.net/qq_18675693/article/details/53556429
相關文章
- java傳送http請求JavaHTTP
- Postman傳送Post請求Postman
- 傳送GET請求 示例
- Java傳送Post請求Java
- SpringMVC中如何傳送GET請求、POST請求、PUT請求、DELETE請求。SpringMVCdelete
- 使用Feign傳送HTTP請求HTTP
- 如何傳送請求以及AJAX
- python傳送HTTP POST請求PythonHTTP
- Postman傳送請求引數是Map格式的請求Postman
- Vue 使用 Axios 傳送請求的請求體問題VueiOS
- nodejs使用request傳送http請求NodeJSHTTP
- java傳送GET和post請求Java
- Python爬蟲(二)——傳送請求Python爬蟲
- Vue中封裝axios傳送請求Vue封裝iOS
- linux用curl傳送post請求Linux
- shell指令碼:批次傳送curl請求指令碼
- 使用requests庫來傳送HTTP請求HTTP
- 使用Postman傳送POST請求的指南Postman
- java傳送get請求帶引數Java
- 以Raw的方式傳送POST請求
- file_get_contents傳送post請求
- jQuery裡如何使用ajax傳送請求jQuery
- vue中使用axios傳送ajax請求VueiOS
- httprequest- post- get -傳送請求HTTP
- react-fetch資料傳送請求React
- 首頁 使用axios 傳送ajax請求iOS
- Go HTTP GET 請求可以傳送 body 嗎GoHTTP
- html頁面中如何傳送ajax請求HTML
- 【Postman】6 Postman 傳送post請求-Json格式PostmanJSON
- curl 傳送 POST 請求的四種方式
- Go使用net/http庫傳送GET請求GoHTTP
- 為何要在componentDidMount裡面傳送請求?
- postman(二):使用postman傳送get or post請求Postman
- 什麼時候會傳送options請求
- 如何在 Go 中傳送表單請求Go
- 前端傳送的請求,是如何請求到後端服務的?前端後端
- 使用 request 和 cheerio 庫來傳送 HTTP 請求HTTP
- 理解ASP.NET Core - 傳送Http請求(HttpClient)ASP.NETHTTPclient
- wireshark抓包curl傳送http2請求HTTP