//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(); } } } }