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();//创建默认的HttpClient实例
HttpPost httpPost = new HttpPost(url);//创建HttpPost请求对象
httpPost.setConfig(requestConfig);//设置参数
List<NameValuePair> nameValuePairs = new ArrayList<>()
for (String keyAndvalue : map.keySet()){
//将值填充到nameValuePairs集合中
nameValuePairs.add(new BasicNameValuePair(keyAndvalue,map.get(keyAndvalue)));
}
//传入的是键值对,将数据设置成UTF-8
UrlEncodedFormEntity Uefentity = new UrlEncodedFormEntity(nameValuePairs,"UTF-8");
Uefentity.setContentEncoding("UTF-8");
Uefentity.setContentType("application/json");
httpPost.setEntity(Uefentity);//将参数设置到请求对象中
String jsonString = JSON.toJSONString(map);//将map转成json字符串
//传入的是json字符串,将数据设置成UTF-8
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();//获取http调用的code状态
String s = EntityUtils.toString(entity, "UTR-8");//将结果转换成指定编码的String类型的数据
}
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");
}