HttpPost请求:
public static void main(String[] args) throws IOException {
String url = null;
Map<String,String> map = new HashMap<>();
RequestConfig requestConfig = RequestConfig.custom()
.setSocketTimeout(2000000).setConnectTimeout(100000)
.setConnectionRequestTimeout(5000).build();
CloseableHttpClient client = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(url);
httpPost.setConfig(requestConfig);
List<NameValuePair> nameValuePairs = new ArrayList<>()
for (String keyAndvalue : map.keySet()){
nameValuePairs.add(new BasicNameValuePair(keyAndvalue,map.get(keyAndvalue)));
}
UrlEncodedFormEntity Uefentity = new UrlEncodedFormEntity(nameValuePairs,"UTF-8");
Uefentity.setContentEncoding("UTF-8");
Uefentity.setContentType("application/json");
httpPost.setEntity(Uefentity);
String jsonString = JSON.toJSONString(map);
StringEntity stringEntity = new StringEntity(jsonString,"UTF-8");
stringEntity.setContentEncoding("UTF-8");
stringEntity.setContentType("application/json");
httpPost.setEntity(stringEntity);
httppost.setHeader("channelNo", channelNo);
httppost.setHeader("signType", signType);
httppost.setHeader("sign", sign);
httppost.setHeader("reqTime", reqTime);
CloseableHttpResponse response = client.execute(httpPost);
HttpEntity entity = response.getEntity();
int statusCode = response.getStatusLine().getStatusCode();
String s = EntityUtils.toString(entity, "UTR-8");
}
HttpGet请求:
String url = null
Map<String,String> map = new HashMap<>()
RequestConfig requestConfig = RequestConfig.custom()
.setSocketTimeout(2000000).setConnectTimeout(100000)
.setConnectionRequestTimeout(5000).build()
CloseableHttpClient httpClient = HttpClients.createDefault()
//将请求的数据拼接到url后面
StringBuffer sb = new StringBuffer(url)
for (String key : map.keySet()){
sb.append(key).append("=").append(map.get(key)).append("&")
}
String newUrl = sb.substring(0, sb.length() - 1)
HttpGet httpGet = new HttpGet(newUrl)
httpGet.setConfig(requestConfig)
CloseableHttpResponse response = httpClient.execute(httpGet)
int statusCode = response.getStatusLine().getStatusCode()
HttpEntity entity = response.getEntity()
String s = EntityUtils.toString(entity, "UTF-8")
}