//post请求,get请求就把HttpPost改成HttpGet public void sendPost(String url){ //创建httpclient对象 CloseableHttpClient httpClient = HttpClients.createDefault(); //设置连接超时时间(非必要设置) RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(3000) .setConnectTimeout(3000).build(); //创建post方式请求对象 HttpPost post = new HttpPost(url); post.setConfig(requestConfig); //设置对应请求接口要求设置的请求头 post.setHeader("Content-Type", "application/json;charset=utf-8"); post.setHeader("Accept", "application/json;charset=utf-8"); post.setHeader("Authorization", "bearer cfd140a6-b29f-40b1-8dba-686b2e5df28b"); //设置普通参数 /*Map<String, Object> params = new HashMap<String, Object>(); params.put("journalName", ""); params.put("issn", "0048-9697"); params.put("year", "2019"); params.put("type", "WOS"); String str = params.toString(); //str --> {journalName=, issn=0048-9697, year=2019, type=WOS} StringEntity stringEntity = new StringEntity(str, "utf-8");*/ //设置参数为json格式 JSONObject params = new JSONObject(); params.put("journalName", ""); params.put("issn", "0048-9697"); params.put("year", "2019"); params.put("type", "WOS"); String str = params.toJSONString(); //str --> {"journalName":"","issn":"0048-9697","year":"2019","type":"WOS"} StringEntity stringEntity = new StringEntity(str, "utf-8"); post.setEntity(stringEntity); // 执行请求并拿到结果 CloseableHttpResponse response = null; String result = null; try { response = httpClient.execute(post); //判断返回状态是否正常 int state = response.getStatusLine().getStatusCode(); if (state != HttpStatus.SC_OK) { System.out.println("connection faild 错误代码:"+state); } //获取结果实体并返回结果 HttpEntity entity = response.getEntity(); result = EntityUtils.toString(entity,"UTF-8"); //返回json处理见下面testGet方法里对json数据的解析处理 //打印结果 System.out.println(result); //释放所有由httpEntity所持有的资源 EntityUtils.consume(entity); } 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(); } } } }
//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(); } } } }