pom文件
<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
</dependency>
package com.mwk.http;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
public class HttpClient {
/**
* 發送 post請求訪問本地應用並根據傳遞參數不同返回不同結果
*
* @param url
* 調用的url
* @param map
* 參數與所傳值
* @return
*/
public static String postHttpCilent(String url, Map<String, Object> map) {
// 創建默認的httpClient實例.
CloseableHttpClient httpclient = HttpClients.createDefault();
// 創建httppost
HttpPost httppost = new HttpPost(url);
// 創建參數隊列
List<BasicNameValuePair> formparams = new ArrayList<>();
Set<String> keys = map.keySet();
for (String key : keys) {
formparams.add(new BasicNameValuePair(key, (String) map.get(key)));
}
UrlEncodedFormEntity uefEntity;
try {
uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8");
httppost.setEntity(uefEntity);
CloseableHttpResponse response = httpclient.execute(httppost);
try {
HttpEntity entity = response.getEntity();
if (entity != null) {
String result = EntityUtils.toString(entity, "UTF-8");
return result;
}
} finally {
response.close();
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
// 關閉連接,釋放資源
try {
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
public static void main(String[] args) {
Map<String, Object> map = new HashMap<>();
String url = "https://www.baidu.com/";
System.out.println(postHttpCilent(url, map));
}
}