package com.brainlong.framework.util.httpclient; import net.sf.json.JSONObject; import org.apache.commons.httpclient.HttpStatus; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.util.EntityUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.net.URLDecoder; public class HttpRequestUtils { private static Logger logger = LoggerFactory.getLogger(HttpRequestUtils. class ); //日誌記錄 /** * httpPost * @param url 路徑 * @param jsonParam 參數 * @return */ public static JSONObject httpPost(String url,JSONObject jsonParam){ return httpPost(url, jsonParam, false ); } /** * post請求 * @param url url地址 * @param jsonParam 參數 * @param noNeedResponse 不須要返回結果 * @return */ public static JSONObject httpPost(String url,JSONObject jsonParam, boolean noNeedResponse){ //post請求返回結果 DefaultHttpClient httpClient = new DefaultHttpClient(); JSONObject jsonResult = null ; HttpPost method = new HttpPost(url); try { if ( null != jsonParam) { //解決中文亂碼問題 StringEntity entity = new StringEntity(jsonParam.toString(), "utf-8" ); entity.setContentEncoding( "UTF-8" ); entity.setContentType( "application/json" ); method.setEntity(entity); } HttpResponse result = httpClient.execute(method); url = URLDecoder.decode(url, "UTF-8" ); /**請求發送成功,並獲得響應**/ if (result.getStatusLine().getStatusCode() == 200 ) { String str = "" ; try { /**讀取服務器返回過來的json字符串數據**/ str = EntityUtils.toString(result.getEntity()); if (noNeedResponse) { return null ; } /**把json字符串轉換成json對象**/ jsonResult = JSONObject.fromObject(str); } catch (Exception e) { logger.error( "post請求提交失敗:" + url, e); } } } catch (IOException e) { logger.error( "post請求提交失敗:" + url, e); } return jsonResult; } /** * 發送get請求 * @param url 路徑 * @return */ public static JSONObject httpGet(String url){ //get請求返回結果 JSONObject jsonResult = null ; try { DefaultHttpClient client = new DefaultHttpClient(); //發送get請求 HttpGet request = new HttpGet(url); HttpResponse response = client.execute(request); /**請求發送成功,並獲得響應**/ if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { /**讀取服務器返回過來的json字符串數據**/ String strResult = EntityUtils.toString(response.getEntity()); /**把json字符串轉換成json對象**/ jsonResult = JSONObject.fromObject(strResult); url = URLDecoder.decode(url, "UTF-8" ); } else { logger.error( "get請求提交失敗:" + url); } } catch (IOException e) { logger.error( "get請求提交失敗:" + url, e); } return jsonResult; } } |