java中调用三方接口post传参时map和jsonobject的区别转换

post方法名及参数为:(具体方法可参考https://www.cnblogs.com/mufengforward/p/10510337.html)

  public static String doPost(String httpUrl, String param) {   ...   }

如果方法参数param是要求以json字符串的形式传递则:

  1. 如果是JSONObject对象转字符串则:String result = HttpUtil.doPost(URL, json.toJsonString());

  2. Map转字符串则需采用:String result = HttpUtil.doPost(URL, JSON.toJSONString(map));

  注:使用map.toString() 时会出现参数解析不到的问题

  因为:json.toJsonString()转换后为:{"name":"ceshi","password":"123456"}

     map.toString()转换后为:{password=123456, name=ceshi}

  对比可知,参数不一致;

 

测试如下:

  public static void main(String[] args) {
        Map map = new HashMap<>();
        map.put("name", "ceshi");
        map.put("password", "123456");
        System.out.println(map.toString()); //{password=123456, name=ceshi}
        System.out.println(JSON.toJSONString(map)); //{"name":"ceshi","password":"123456"}

        JSONObject json = new JSONObject();
        json.put("name", "ceshi");
        json.put("password", "123456");
        System.out.println(json.toJSONString()); //{"name":"ceshi","password":"123456"}
    }

 

转载于:https://www.cnblogs.com/mufengforward/p/10707484.html

Java代码调用post接口传参的案例可以分为以下几个步骤: 1. 导入相关依赖 一般情况下,我们需要导入HTTP客户端的相关依赖,推荐使用Apache HttpComponents或OkHttp来实现HTTP请求。 2. 构造HTTP请求 根据接口文档给出的API地址和请求方法,我们可以构造对应的HTTP请求对象,设置请求头、参数等内容。例如: ``` HttpPost httpPost = new HttpPost("http://example.com/api/user"); httpPost.setHeader("Content-Type", "application/json;charset=UTF-8"); JSONObject params = new JSONObject(); params.put("name", "张三"); params.put("age", 20); StringEntity stringEntity = new StringEntity(params.toString(), ContentType.APPLICATION_JSON); httpPost.setEntity(stringEntity); ``` 3. 发送请求并处理响应 使用HttpClient或OkHttpClient客户端发送请求,并阻塞等待服务器响应。一般情况下,我们需要根据响应状态码和内容类型等信息来判断请求是否成功,并解析响应内容。 ``` CloseableHttpClient httpClient = HttpClients.createDefault(); CloseableHttpResponse response = httpClient.execute(httpPost); int statusCode = response.getStatusLine().getStatusCode(); if (statusCode == HttpStatus.SC_OK) { HttpEntity entity = response.getEntity(); String responseContent = EntityUtils.toString(entity, Charset.forName("UTF-8")); JSONObject responseJson = JSON.parseObject(responseContent); // 处理响应内容 } ``` 以上是Java代码调用post接口传参的基本流程,当然具体实现还需要按照实际需求进行调整。在实际项目开发,我们也可以使用各种HTTP请求框架封装,遵循开闭原则,提高代码复用性和可维护性。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值