基於HttpClient JSONObject與JSONArray的使用

package com.spring.utils;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
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 Object httpPost(String url,JSONObject jsonParam){
        return httpPost(url, jsonParam, false);
    }
 
    /**
     * post請求
     * @param url         url地址
     * @param jsonParam     參數
     * @param noNeedResponse    不須要返回結果
     * @return
     */
    public static Object httpPost(String url,JSONObject jsonParam, boolean noNeedResponse){
        //post請求返回結果
    	HttpClient httpClient = new DefaultHttpClient();
        Object 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 strResult = "";
                try {
                    /**讀取服務器返回過來的json字符串數據**/
                	strResult = EntityUtils.toString(result.getEntity());
                    if (noNeedResponse) {
                        return null;
                    }
                    if(strResult.startsWith("[") && strResult.endsWith("]")){  
                    	 /**把json字符串轉換成json對象數組**/
                    	 jsonResult = JSONArray.fromObject(strResult); // 首先把字符串轉成 JSONArray  對象
                    }else if(strResult.startsWith("{") && strResult.endsWith("}"))
                    {
                    	  /**把json字符串轉換成json對象**/
                    	jsonResult = JSONObject.fromObject(strResult);
                    }else
                    {
                    	return strResult;
                    }
                } catch (Exception e) {
                    logger.error("post請求提交失敗:" + url, e);
                }
            }
        } catch (IOException e) {
            logger.error("post請求提交失敗:" + url, e);
        }
        return jsonResult;
    }
 
 
    /**
     * 發送get請求
     * @param url    路徑
     * @return
     */
    public static Object httpGet(String url){
        //get請求返回結果
        Object jsonResult = null;
        String strResult = null;
        try {
        	HttpClient client = new DefaultHttpClient();
            //發送get請求
            HttpGet request = new HttpGet(url);
            HttpResponse response = client.execute(request);
 
            /**請求發送成功,並獲得響應**/
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                /**讀取服務器返回過來的json字符串數據**/
                strResult = EntityUtils.toString(response.getEntity());
                /**把json字符串轉換成json對象**/
                //接收{}對象,此處接收數組對象會有異常  
                if(strResult.startsWith("[") && strResult.endsWith("]")){  
                	jsonResult = JSONArray.fromObject(strResult); // 首先把字符串轉成 JSONArray  對象
                }else if(strResult.startsWith("{") && strResult.endsWith("}"))
                {
                	jsonResult = JSONObject.fromObject(strResult);
                }else
                {
                	return strResult;
                }
                url = URLDecoder.decode(url, "UTF-8");
            } else {
                logger.error("get請求提交失敗:" + url);
            }
        }catch (IOException e) {
            logger.error("get請求提交失敗:" + url, e);
        }
        return jsonResult;
    }
    
}
相關文章
相關標籤/搜索