POST和GET請求
阿新 • • 發佈:2020-12-24
public static String doPost(String url){ //建立httpClient物件 CloseableHttpClient httpClient = HttpClients.createDefault(); CloseableHttpResponse response = null; String result = ""; try{ //建立http請求 HttpPost httpPost = new HttpPost(url); httpPost.addHeader("Content-Type", "application/json"); //建立請求內容 String jsonStr = "{\"qry_by\":\"name\", \"name\":\"Tim\"}"; StringEntity entity = new StringEntity(jsonStr); httpPost.setEntity(entity); response = httpClient.execute(httpPost); result= EntityUtils.toString(response.getEntity(),"utf-8"); System.out.println(result); }catch (Exception e){ e.printStackTrace(); }finally { //關閉資源 if(response != null){ try { response.close(); }catch (IOException ioe){ ioe.printStackTrace(); } } if(httpClient != null){ try{ httpClient.close(); }catch (IOException ioe){ ioe.printStackTrace(); } } } return result; }
public static String doGet(String url){ CloseableHttpClient httpClient = null; CloseableHttpResponse response = null; String result = ""; try{ //通過預設配置建立一個httpClient例項 httpClient = HttpClients.createDefault(); //建立httpGet遠端連線例項 HttpGet httpGet = new HttpGet(url); //httpGet.addHeader("Connection", "keep-alive"); //設定請求頭資訊 httpGet.addHeader("Accept", "application/json"); //配置請求引數 RequestConfig requestConfig = RequestConfig.custom() .setConnectTimeout(35000) //設定連線主機服務超時時間 .setConnectionRequestTimeout(35000)//設定請求超時時間 .setSocketTimeout(60000)//設定資料讀取超時時間 .build(); //為httpGet例項設定配置 httpGet.setConfig(requestConfig); //執行get請求得到返回物件 response = httpClient.execute(httpGet); //通過返回物件獲取返回資料 HttpEntity entity = response.getEntity(); //通過EntityUtils中的toString方法將結果轉換為字串,後續根據需要處理對應的reponse code result = EntityUtils.toString(entity); System.out.println(result); }catch (ClientProtocolException e){ e.printStackTrace(); }catch (IOException ioe){ ioe.printStackTrace(); }catch (Exception e){ e.printStackTrace(); }finally { //關閉資源 if(response != null){ try { response.close(); }catch (IOException ioe){ ioe.printStackTrace(); } } if(httpClient != null){ try{ httpClient.close(); }catch (IOException ioe){ ioe.printStackTrace(); } } } return result; }