FastJson-从httpEntity到Json

在对接第三方接口时返还的数据是HttpResponse,如何从response中取到相应的code值呢?特作出一个总结:

1.从response中可以得到httpEntity实体

   HttpEntity entity = response.getEntity();
  EntityUtils.toString(response.getEntity())

输出的结果为:

2.String转换为JsonObject格式

JSONObject jsonObject = JSON.parseObject(EntityUtils.toString(response.getEntity()));

3.提取code

String responseCode = jsonObject.getString("code");

得到code值之后,就可以进行相应的判断,执行业务流程啦。。。

 希望对看到的小伙伴们有所帮助,不喜勿喷。欢迎各位留言指正。。。。。 

以下是Java使用fastjson接收带有GBK字符集的http请求的示例代码,其中包括了中文注释: import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.nio.charset.Charset; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.parser.Feature; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.ContentType; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; public class FastJsonDemo { public static void main(String[] args) throws IOException { // 构建HttpClient对象 HttpClient httpClient = HttpClients.createDefault(); // 通过HttpPost创建请求对象 HttpPost httpPost = new HttpPost("http://example.com/api"); // 设置请求参数 JSONObject jsonObject = new JSONObject(); jsonObject.put("param1", "value1"); jsonObject.put("param2", "value2"); StringEntity stringEntity = new StringEntity(jsonObject.toString(), ContentType.APPLICATION_JSON); httpPost.setEntity(stringEntity); // 发送请求并获取响应 HttpResponse httpResponse = httpClient.execute(httpPost); HttpEntity httpEntity = httpResponse.getEntity(); // 获取响应结果,并指定编码为GBK String result = EntityUtils.toString(httpEntity, Charset.forName("GBK")); // 解析响应结果,使用fastjson库进行解析 JSONObject responseJson = JSON.parseObject(result, Feature.InitStringFieldAsEmpty); // 输出解析结果 System.out.println("解析结果:"); System.out.println(responseJson.toJSONString()); } }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值