注:主要是用于調用接口使用的http請求方法,分為post和get倆種。
HttpClient和HttpsURLConnection的區別:
/*** 直接訪問請求時可以用HttpsURLConnection,但* 可能需要用戶登錄而且具有相應的權限才可訪問該頁面。* 在這種情況下,就需要涉及session、Cookie的處理了,* 如果打算使用HttpURLConnection來處理這些細節,* 當然也是可能實現的,只是處理起來難度就大了。 為了更好地處理向Web站點請求,包括處理Session、Cookie等細節問題, Apache開源組織提供了一個HttpClient項目,看它的名稱就知道, 它是一個簡單的HTTP客戶端(并不是瀏覽器),可以用于發送HTTP請求, 接收HTTP響應。但不會緩存服務器的響應, 不能執行HTML頁面中嵌入的javaScript代碼; 也不會對頁面內容進行任何解析、處理。 簡單來說,HttpClient就是一個增強版的HttpURLConnection, HttpURLConnection可以做的事情HttpClient全部可以做; HttpURLConnection沒有提供的有些功能, HttpClient也提供了,但它只是關注于如何發送請求、接收響應,以及管理HTTP連接。 使用HttpClient發送請求、接收響應很簡單,只要如下幾步即可。 創建HttpClient對象。 如果需要發送GET請求,創建HttpGet對象;如果需要發送POST請求,創建HttpPost對象。 如果需要發送請求參數, 可調用HttpGet、HttpPost共同的setParams(HetpParams params)方法來添加請求參數; 對于HttpPost對象而言,也可調用setEntity(HttpEntity entity)方法來設置請求參數。 調用HttpClient對象的execute(HttpUriRequest request)發送請求, 執行該方法返回一個HttPResponse。 調用HttpResponse的getAllHeaders()、getHeaders(String name)等方法可獲取服務器的響應頭; 調用HttpResponse的getEntity()方法可獲取HttpEntity對象,該對象包裝了服務器的響應內容。 程序可通過該對象獲取服務器的響應內容。* @return*/
public static String post(String url,Map<String, Object> params) throws ClientProtocolException, IOException
{String content = null;List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();if(params!=null){Set<String> keySet = params.keySet(); for(String key : keySet) { nameValuePairs.add(new BasicNameValuePair(key, String.valueOf(params.get(key)))); } }CloseableHttpClient httpclient = HttpClientBuilder.create().build();HttpPost httppost = new HttpPost(url);httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs,"utf-8"));CloseableHttpResponse response = httpclient.execute(httppost);if(200!=response.getStatusLine().getStatusCode()){httppost.releaseConnection();return null;}HttpEntity entity = response.getEntity();content = EntityUtils.toString(entity, "utf-8");httppost.releaseConnection();return content;}public static String get(String url) throws ClientProtocolException, IOException{CloseableHttpClient httpclient = HttpClientBuilder.create().build(); //HttpGet httpget = new HttpGet("http://www.baidu.com/"); HttpGet httpget = new HttpGet(url); RequestConfig requestConfig = RequestConfig.custom() .setConnectionRequestTimeout(1000) .setConnectTimeout(3000) .setSocketTimeout(4000).build(); httpget.setConfig(requestConfig); CloseableHttpResponse response = httpclient.execute(httpget); System.out.println("StatusCode -> " + response.getStatusLine().getStatusCode());if(200!=response.getStatusLine().getStatusCode()){httpget.releaseConnection();return null;} HttpEntity entity = response.getEntity(); String jsonStr = EntityUtils.toString(entity);//, "utf-8"); System.out.println(jsonStr); httpget.releaseConnection(); return jsonStr;}新聞熱點
疑難解答