注:主要是用于調(diào)用接口使用的http請求方法,分為post和get倆種。
HttpClient和HttpsURLConnection的區(qū)別:
/*** 直接訪問請求時可以用HttpsURLConnection,但* 可能需要用戶登錄而且具有相應(yīng)的權(quán)限才可訪問該頁面。* 在這種情況下,就需要涉及session、Cookie的處理了,* 如果打算使用HttpURLConnection來處理這些細節(jié),* 當然也是可能實現(xiàn)的,只是處理起來難度就大了。 為了更好地處理向Web站點請求,包括處理Session、Cookie等細節(jié)問題, Apache開源組織提供了一個HttpClient項目,看它的名稱就知道, 它是一個簡單的HTTP客戶端(并不是瀏覽器),可以用于發(fā)送HTTP請求, 接收HTTP響應(yīng)。但不會緩存服務(wù)器的響應(yīng), 不能執(zhí)行HTML頁面中嵌入的javaScript代碼; 也不會對頁面內(nèi)容進行任何解析、處理。 簡單來說,HttpClient就是一個增強版的HttpURLConnection, HttpURLConnection可以做的事情HttpClient全部可以做; HttpURLConnection沒有提供的有些功能, HttpClient也提供了,但它只是關(guān)注于如何發(fā)送請求、接收響應(yīng),以及管理HTTP連接。 使用HttpClient發(fā)送請求、接收響應(yīng)很簡單,只要如下幾步即可。 創(chuàng)建HttpClient對象。 如果需要發(fā)送GET請求,創(chuàng)建HttpGet對象;如果需要發(fā)送POST請求,創(chuàng)建HttpPost對象。 如果需要發(fā)送請求參數(shù), 可調(diào)用HttpGet、HttpPost共同的setParams(HetpParams params)方法來添加請求參數(shù); 對于HttpPost對象而言,也可調(diào)用setEntity(HttpEntity entity)方法來設(shè)置請求參數(shù)。 調(diào)用HttpClient對象的execute(HttpUriRequest request)發(fā)送請求, 執(zhí)行該方法返回一個HttPResponse。 調(diào)用HttpResponse的getAllHeaders()、getHeaders(String name)等方法可獲取服務(wù)器的響應(yīng)頭; 調(diào)用HttpResponse的getEntity()方法可獲取HttpEntity對象,該對象包裝了服務(wù)器的響應(yīng)內(nèi)容。 程序可通過該對象獲取服務(wù)器的響應(yīng)內(nèi)容。* @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;}新聞熱點
疑難解答