【问题标题】:RestTemplate post in json,getBody is nulljson 中的 RestTemplate 帖子,getBody 为空
【发布时间】:2017-06-28 06:07:08
【问题描述】:

我遇到这样的情况:我需要调用一个外部接口,它使用第一种方式。但是现在,我需要使用第二种方式,遗憾的是它不起作用。

第一种方式

try {
        String url = "http://domain/service";
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);
        List nvps = new ArrayList();
        nvps.add(new BasicNameValuePair("jsoncommond", jsoncommond));
        httpPost.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));
        CloseableHttpResponse response = httpclient.execute(httpPost);
        HttpEntity entity = response.getEntity();
        String APIresult = "";
        if (entity != null) {
            APIresult = EntityUtils.toString(entity, "utf-8");
        }
        System.out.println("==="+ APIresult);
        EntityUtils.consume((org.apache.http.HttpEntity) entity);
        response.close();
        response.close();
        httpclient.close();
    } catch (Exception e){
        e.printStackTrace();
    }

第二种方式

RestTemplate restTemplate = new RestTemplate();
    restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());

    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);

    HttpEntity<String> entity = new HttpEntity<String>(jsoncommond,headers);

    ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.POST,entity,String.class);

    System.out.println("-----"+response+"\n----=-"+response.getBody());

这样的结果,response.getBody() 为空

**-----<200 OK,{Server=[], Content-Type=[text;html;charset=UTF-8], Transfer-Encoding=[chunked], Date=[Wed, 28 Jun 2017 05:26:22 GMT]}>
----=-null**

jsoncommond 是这样的 json 字符串:

    {
      "request": {
        "aPPID": "aa",
        "aPPKEY": "bb"
      },
      "data": {
        "address": "x",
        "city": "y",
        "country": "z"
      }
    }

这是为什么呢?请帮帮我!

【问题讨论】:

    标签: java spring resttemplate


    【解决方案1】:

    看起来 WS 需要 jsoncommond 参数,但您将其作为正文发送。

    试试下面的代码。

    MultiValueMap<String, Object> variables = new LinkedMultiValueMap<>();
    variables.put("jsoncommond", Collections.singletonList(convertToJSON(jsoncommond)));
    
    HttpEntity<String> entity = new HttpEntity<String>(variables, headers);
    ...
    

    更新:

    private String convertToJSON(Object obj) {
        ObjectMapper mapper = new ObjectMapper();
        try {
            if (obj == null) {
                return null;
            } else if (obj instanceof String) {
                return (String) obj;
            }
            return mapper.writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            throw new SOAControllerInvocationException("Cannot serialize to JSON " + obj, e);
        }
    }
    

    【讨论】:

    • convertToJSON 是什么?这是我的 jsoncommondp[
    • 这只是将值转换为 json 字符串的东西/实际上您可以尝试同时使用 - 直接对象和对象的 JSON 字符串表示。添加了我的功能
    • 这是我的 jsoncommond 变量,例如:String jsoncommond ="{" +"\"request\":{" +" \"aPPID\":\"aaa\"," +" \"aPPKEY\":\"bbb\"" +" }," +"\"data\":{" +" \"address\":\"xx\"," +" \"city\":\"yy\"," +" \"country\":\"zz\"" +" }" +" }";。jsoncommond 不是对象。所以,这是否需要使用您的 convertToJSON
    • 您仍然可以使用该功能。如果参数是字符串,它会按原样返回 OR 当然你可以跳过转换逻辑
    • 好的,我明白了。我试试。非常感谢。
    猜你喜欢
    • 1970-01-01
    • 2012-09-25
    • 2023-03-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多