//get请求
private String testGet() {
//创建 CloseableHttpClient
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = null;
String result = null;
try {
URIBuilder uri = new URIBuilder("请求路径");
//get请求带参数
List<NameValuePair> list = new LinkedList<>();
BasicNameValuePair param1 = new BasicNameValuePair("key1", "value1");
BasicNameValuePair param2 = new BasicNameValuePair("key2", "value2");
list.add(param1);
list.add(param2);
uri.setParameters(list);
HttpGet httpGet = new HttpGet(uri.build());
//设置请求状态参数
RequestConfig requestConfig = RequestConfig.custom()
.setConnectionRequestTimeout(3000)
.setSocketTimeout(3000)
.setConnectTimeout(3000).build();
httpGet.setConfig(requestConfig);
response = httpClient.execute(httpGet);
int status = response.getStatusLine().getStatusCode();//获取返回状态值
if (status == HttpStatus.SC_OK) {//请求成功
HttpEntity httpEntity = response.getEntity();
if(httpEntity != null){
result = EntityUtils.toString(httpEntity, "UTF-8");
EntityUtils.consume(httpEntity);//关闭资源
JSONObject jsonResult = JSONObject.fromObject(result);
// JSONObject如下格式
/*{
"data ": [
{
"name": "*",
"value": "*",
}
],
"success ": true
}*/
JSONArray jsonArray = jsonResult.getJSONArray("data");
for (int i = 0; i < jsonArray.size(); i++) {//只取一个值返回
result = jsonArray.getJSONObject(i).getString("对应key")
}
return result;
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if(response != null){
try {
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(httpClient != null){
try {
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return result;
}
//post请求
private void testPost(){
HttpPost httpPost = new HttpPost("请求路径");
CloseableHttpClient client = HttpClients.createDefault();
List params = new ArrayList();
params.add(new BasicNameValuePair("key1", "value1"));
params.add(new BasicNameValuePair("key2", "value2"));
try {
HttpEntity httpEntity = new UrlEncodedFormEntity(params, "UTF-8");
httpPost.setEntity(httpEntity);
response = client.execute(httpPost);
} catch (Exception e) {
e.printStackTrace();
} finally {
if(response != null){
try {
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(client != null){
try {
client.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}