1. 程式人生 > >java實現Http請求

java實現Http請求

以下程式碼是本人在實際工作中總結出來的,個人感覺還是比較精簡幹練的,

get請求:


	public static String getMethod(String url,Map<String,Object> dataMap) throws  Exception{
		CloseableHttpClient httpClient = null;
		CloseableHttpResponse response = null;
		try {
			httpClient = HttpClients.createDefault();
			//封裝請求引數
			List<NameValuePair> params = Lists.newArrayList();
			for (Entry<String, Object> entry: dataMap.entrySet()) {
				params.add(new BasicNameValuePair(entry.getKey(), entry.getValue().toString()));
			}
			String str = EntityUtils.toString(new UrlEncodedFormEntity(params, Consts.UTF_8));
			//建立Get請求
			HttpGet httpGet = new HttpGet(url+"?"+str);
			//超時設定
			RequestConfig requestConfig = RequestConfig.custom()
			        .setConnectTimeout(5000)
			        .setConnectionRequestTimeout(1000)
			        .setSocketTimeout(5000)
			        .build();
			httpGet.setConfig(requestConfig);
			//執行Get請求,
			response = httpClient.execute(httpGet);
			//得到響應體
            return EntityUtils.toString(response.getEntity(), Consts.UTF_8); 
		}finally{
			//消耗實體內容
			close(response);
			//關閉相應 丟棄http連線
			close(httpClient);
		}
	}

post請求

public static String postMethod(String url,Map<String,Object> dataMap) throws  Exception{
		CloseableHttpClient httpClient = null;
		CloseableHttpResponse response = null;
		try {
			httpClient = HttpClients.createDefault();
			//封裝請求引數
			String params = JSONObject.toJSONString(dataMap);
			System.out.println(url+"?"+params);
			//建立post請求
			HttpPost httpPost = new HttpPost(url);
			//執行post請求,
			httpPost.addHeader("Content-Type", "application/json");
			//設定超時
			RequestConfig requestConfig = RequestConfig.custom()
				        .setConnectTimeout(5000)
				        .setConnectionRequestTimeout(1000)
				        .setSocketTimeout(5000).build();
			httpPost.setConfig(requestConfig);
			HttpEntity reqEntity = new StringEntity(params, Consts.UTF_8);
			httpPost.setEntity(reqEntity);
			response = httpClient.execute(httpPost);
            //得到響應體
            return EntityUtils.toString(response.getEntity(), Consts.UTF_8); 
		}finally{
			//消耗實體內容
			close(response);
			//關閉相應 丟棄http連線
			close(httpClient);
		}
	}

關閉流

	private static void close(Closeable closable){
		//關閉輸入流,釋放資源
		if(closable != null){
			try {
				closable.close();
			} catch (IOException e) {
				log.error("IO流關閉異常",e);
			}
		}
	}