• 基于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;
        }
        
    }
    

      

  • 相关阅读:
    十六进制计算器
    USB 3.0规范中译本 第7章 链路层
    from表单POST提交nodejs
    07_通过谷歌封装的api操作数据库delete&insert
    06_直接执行sql操作数据库delete&update
    05_直接执行sql操作数据库
    04_数据库升级onUpgrade&ondowngrade
    03_通过OpenHelper获取SqliteDatabase对象
    02_SQliteOpenHelper介绍&oncreate方法介绍
    00_前情回顾&今日展望
  • 原文地址:https://www.cnblogs.com/coinbt/p/8320912.html
Copyright © 2020-2023  润新知