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

  

转载于:https://www.cnblogs.com/coinbt/p/8320912.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要实现一个 Java 的 HTTP POST 接口,既支持 JSONObject,又支持 JSONArray 入参,非 String 格式,你可以使用 HTTP 请求库,比如 Apache HttpClient 或者 OkHttp,具体实现步骤如下: 1. 导入 HTTP 请求库的相关依赖。 2. 创建一个 HttpClient 对象,用于发送 HTTP 请求。 3. 创建一个 HttpPost 对象,用于发送 POST 请求。 4. 设置请求头信息,比如 Content-Type,Accept 等。 5. 创建 JSON 请求体,可以是一个 JSONObject 或者 JSONArray 对象。 6. 将 JSON 请求体转换成 byte[] 数组,并设置到 HttpPost 请求体中。 7. 执行 HttpPost 请求,并获取响应结果。 8. 将响应结果转换成 JSON 对象或者 JSON 数组,使用相应的方法进行解析即可。 下面是一个使用 Apache HttpClient 实现的 HTTP POST 接口,支持 JSONObjectJSONArray 入参的示例代码: ```java import org.apache.http.HttpEntity; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.ByteArrayEntity; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; import org.json.JSONArray; import org.json.JSONObject; import java.nio.charset.StandardCharsets; public class PostJson { public static void main(String[] args) throws Exception { // 创建 HttpClient 对象 HttpClient httpClient = HttpClients.createDefault(); // 创建 HttpPost 对象 HttpPost httpPost = new HttpPost("http://localhost:8080/post"); // 设置请求头信息 httpPost.setHeader("Content-Type", "application/json"); // 创建 JSON 请求体 JSONObject jsonObject = new JSONObject(); jsonObject.put("name", "John"); jsonObject.put("age", 30); JSONArray jsonArray = new JSONArray(); jsonArray.put("apple"); jsonArray.put("banana"); jsonArray.put("orange"); // 将 JSON 请求体转换成 byte[] 数组,并设置到 HttpPost 请求体中 HttpEntity httpEntity = new ByteArrayEntity(jsonObject.toString().getBytes(StandardCharsets.UTF_8)); httpPost.setEntity(httpEntity); // 执行 HttpPost 请求,并获取响应结果 String response = EntityUtils.toString(httpClient.execute(httpPost).getEntity(), StandardCharsets.UTF_8); // 将响应结果转换成 JSON 对象或者 JSON 数组,使用相应的方法进行解析即可 JSONObject jsonResponse = new JSONObject(response); System.out.println(jsonResponse); JSONArray jsonArrayResponse = new JSONArray(response); System.out.println(jsonArrayResponse); } } ``` 注意:上述代码仅供参考,实际应用中需要根据具体需求进行修改。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值