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
相關文章
- Postman傳送Post請求Postman
- Java傳送Post請求Java
- 傳送GET請求 示例
- perl傳送http請求HTTP
- java傳送http請求JavaHTTP
- 如何傳送請求以及AJAX
- C# 傳送POST請求C#
- 使用HttpClient傳送GET請求HTTPclient
- 使用httpclient傳送http請求HTTPclient
- SpringMVC中如何傳送GET請求、POST請求、PUT請求、DELETE請求。SpringMVCdelete
- Zttp 傳送 form params 請求 而非 JSON 請求ORMJSON
- 【轉】怎麼用PHP傳送HTTP請求(POST請求、GET請求)?PHPHTTP
- java傳送GET和post請求Java
- 使用Feign傳送HTTP請求HTTP
- python傳送HTTP POST請求PythonHTTP
- post 封裝Map 傳送請求封裝
- PHP傳送POST和GET請求PHP
- postman傳送請求使用篇(二)Postman
- Python傳送請求代tokenPython
- 用Fiddler 傳送post請求
- .net 後臺 傳送http請求HTTP
- 通過PowerShell傳送TCP請求TCP
- 使用C#傳送POST請求C#
- Postman傳送請求引數是Map格式的請求Postman
- java傳送post請求 ,請求資料放到body裡Java
- Vue 使用 Axios 傳送請求的請求體問題VueiOS
- linux用curl傳送post請求Linux
- 以Raw的方式傳送POST請求
- Python爬蟲(二)——傳送請求Python爬蟲
- Vue中封裝axios傳送請求Vue封裝iOS
- httprequest- post- get -傳送請求HTTP
- jQuery裡如何使用ajax傳送請求jQuery
- 使用requests庫來傳送HTTP請求HTTP
- nodejs使用request傳送http請求NodeJSHTTP
- php 利用socket傳送GET,POST請求PHP
- java傳送http的get、post請求JavaHTTP
- 實現傳送多個Ajax請求
- 什麼時候會傳送options請求