发起http的post请求入参格式为json

发起http的post请求入参格式为json字符串

接到公司的一个需求,给了我一个接口让我获取里面的数据并保存到数据库中。

这里我在把发起的http请求类贴在下面,需要在pom.xml导入如下jar

<dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>fastjson</artifactId>
      <version>1.2.58</version>
</dependency>
<dependency>
      <groupId>org.apache.httpcomponents</groupId>
      <artifactId>httpclient</artifactId>
      <version>4.5.8</version>
      <scope>compile</scope>
</dependency>

如下是发起post请求代码

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.util.EntityUtils;
import org.apache.http.protocol.HTTP;

import java.io.IOException;

/**
 *  Author wei风中的一匹狼
 *  http发送post请求
 *  url 请求的url地址
 *  jsonObject 需要传递的json字符串参数
 *  encoding 编码格式
 */
public class SendPost {
    public static String sendPost(String url, JSONObject jsonObject, String encoding) throws IOException {
        String body = "";
        CloseableHttpClient client = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);
        StringEntity s = new StringEntity(jsonObject.toString(), "utf-8");
        s.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,"application/json"));
        httpPost.setEntity(s);
        System.out.println("请求地址:"+url);
        httpPost.setHeader("Content-type", "application/json");
        httpPost.setHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
        CloseableHttpResponse response = client.execute(httpPost);
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            body = EntityUtils.toString(entity, encoding);
        }
        EntityUtils.consume(entity);
        response.close();
        //json.parse这一步的原因是,返回的json字符创是Unicode编码格式,需要通过json.parse解析成中文格式并h返回
        return String.valueOf(JSON.parse(body));
    }
}
入参为json字符串

类似如下这种

{
	"user_uuid":"dc2f8821",
	"exam_user_name":"yy"
}

这里需要用到阿里巴巴的fastjson,用JSONObject方法转换成json格式,然后把Eveninput当做入参。

JSONObject Eveninput = new JSONObject();
        Eveninput.put("user_uuid","user_uuid");
        Eveninput.put("exam_user_name","exam_user_name");

下面贴上我的请求代码

@Transactional(rollbackFor = Exception.class)
    public void httpRequest(String username) {
        JSONObject Eveninput = new JSONObject();//把字符串入参转换成json格式
        Eveninput.put("user_uuid",useruuid);
        Eveninput.put("exam_user_name",username);
        String json = null;
        try {
            json = SendPost.sendPost(url, Eveninput, "utf-8");//此处发起http请求,返回json数据
        } catch (IOException e) {
            e.printStackTrace();
        }
        //就可以输出返回的json数据了
        System.out.println(json);
    }
下面讲一下怎么把json格式数据转换成java对象即JavaBean

这里我贴上一个练习的代码,导入jar的时候一点要注意“import com.alibaba.fastjson.JSON”,一定是fastjson

package com.jiangwei;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;

import java.util.*;

/**
 * Hello world!
 * Author wei风中的一匹狼
 */
public class App {
    public static void main(String[] args) {
        //普通map
        String jsonString1 = "{\"param5\":\"value5\",\"param3\":\"value3\",\"param4\":\"value4\",\"param1\":\"value1\",\"param2\":\"value2\"}";
        System.out.println(jsonString1);
        Map<String,String> stringStringMap = (Map<String,String>)JSON.parse(jsonString1);
        for (String s : stringStringMap.keySet()) {
            System.out.println(s + "==>" +stringStringMap.get(s));
        }
        System.out.println("1===================================================");

        //List<Map<String,String>>
        String jsonString2 = "[{\"param5\":\"value5\",\"param3\":\"value3\",\"param4\":\"value4\",\"param1\":\"value1\",\"param2\":\"value2\"},{\"p1\":\"v1\",\"p2\":\"v2\",\"p3\":\"v3\",\"p4\":\"v4\",\"p5\":\"v5\"}]";
        System.out.println(jsonString2);
        List<Map<String,String>> mapList = JSON.parseObject(jsonString2, new TypeReference<List<Map<String,String>>>(){});
        for (Map<String, String> stringObjectMap : mapList) {
            for (String s : stringObjectMap.keySet()) {
                System.out.println(s + "==>" + stringObjectMap.get(s));
            }
        }
        System.out.println("2===================================================");

        //Map<String,Object> ==> Object还能够进行分解
        String jsonString3 = "{\"count\":2,\"list\":[{\"param5\":\"value5\",\"param3\":\"value3\",\"param4\":\"value4\",\"param1\":\"value1\",\"param2\":\"value2\"},{\"p1\":\"v1\",\"p2\":\"v2\",\"p3\":\"v3\",\"p4\":\"v4\",\"p5\":\"v5\"}]}";
        System.out.println(jsonString3);
        Map<String,Object> map = JSON.parseObject(jsonString3);
        System.out.println(map.get("count"));
        String tempjsonString3 = map.get("list").toString();
        System.out.println(tempjsonString3);
        List<Map<String,String>> mapList2 = JSON.parseObject(tempjsonString3, new TypeReference<List<Map<String,String>>>(){});
        for (Map<String, String> stringObjectMap : mapList2) {
            for (String s : stringObjectMap.keySet()) {
                System.out.println(s + "==>" + stringObjectMap.get(s));
            }
        }
        System.out.println("3===================================================");

        //解析已有的对象
        String jsonString4 = "[{\"age\":12,\"date\":1465475917155,\"name\":\"s1\"},{\"age\":12,\"date\":1465475917175,\"name\":\"s2\"},{\"age\":12,\"date\":1465475917175,\"name\":\"s3\"},{\"age\":12,\"date\":1465475917175,\"name\":\"s4\"},{\"age\":12,\"date\":1465475917175,\"name\":\"s5\"},{\"age\":12,\"date\":1465475917175,\"name\":\"s6\"}]";
        System.out.println(jsonString4);
        List<Student> studentList = JSON.parseArray(jsonString4,Student.class);
        for (Student student : studentList) {
            System.out.println(student.getName());
        }
        System.out.println("4===================================================");

        //解析已有的对象的另一种方式
        System.out.println(jsonString4);
        List<Student> studentList2 = JSON.parseObject(jsonString4,new TypeReference<List<Student>>(){});
        for (Student student : studentList2) {
            System.out.println(student.getName());
        }
    }
}
这里需要注意一下下面这三个方法
JSON.parseArray()//针对数组
JSON.parseObject()//针对对象
JSON.parse()//针对属性
package jsonTest;
 
import com.alibaba.fastjson.JSON;
 
/**
 * @author wujiang
 * @version 1.0.0.
 * @date 2017/4/30
 */
public class jsonTest {
    public static void main(String[] args) {
        /**
         * json字符串转化为对象
         */
        String jsonString = "{name:'Antony',age:'12',sex:'male',telephone:'88888'}";
        Staff staff = JSON.parseObject(jsonString, Staff.class);
        System.out.println(staff.toString());
 
        /**
         * 对象转化为json字符串
         */
        String jsonStr = JSON.toJSONString(staff);
        System.out.println(jsonStr);
    }
}
  • 5
    点赞
  • 27
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值