通过使用来自spring的rest模板通过post调用发送json数据

时间:2014-04-04 07:43:53

标签: java json spring resttemplate

我一直收到一个错误,说这不是有效的json数据并且一直收到错误400.我不认为我的实现是正确格式化数据。 目标:尝试使用休息模板进行发布呼叫,方法是将JSON数据作为正文传递。似乎从map转换为json数据时,它没有正确转换为json。

public void GetJsonData(String name, String city) {
        Map<String, String> map = new HashMap<String, String>();
        map.put("api_key", apikey);



map.put("venue_queries", "[{'name':'"+name+"', 'location': {'locality': '"+city+"'}}]");

        try {
            String resp = GlobalHelper.calltestService(RestServicesUrl, map);
            System.out.println(resp);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }


public String calltestService(String url, Map<String, String> data) throws Exception {
        RestTemplate rest = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
        ResponseEntity<String> response = new ResponseEntity<String>(headers, HttpStatus.OK);
        rest.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
            Gson gson = new Gson();
            System.out.println(gson.toJson(data));
        try {
            response = rest.postForEntity(url, gson.toJson(data), String.class);
            System.out.println(response.getBody()); 
            System.out.println(response.getHeaders());
            return response.getBody();
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("error in post entity");
            return "error";
        }
    }

1 个答案:

答案 0 :(得分:1)

是的,您生成的JSON无效

{
    "venue_queries": "[{\u0027name\u0027:\u0027yo\u0027, \u0027location\u0027: {\u0027locality\u0027: \u0027Solares\u0027}}]",
    "api_key": "asfasdfasfdasdfasdfa"
}

你JSON无效,因为GSON默认转义HTML字符并将单引号作为等效的unicode字符代码U + 0027

如果您停用Gson HTMLEscaping

GsonBuilder builder = new GsonBuilder();
builder.disableHtmlEscaping();
Gson gson = builder.create();

你会得到

{
    "venue_queries": "[{'name':'yo', 'location': {'locality': 'Solares'}}]",
    "api_key": "asfasdfasfdasdfasdfa"
}

无论如何,你的JSON仍然不正确。

您必须在地图venue_queries using double quotes

中修复"关键内容
map.put("venue_queries", "[{\"name\":\""+name+"\", \"location\": {\"locality\": \""+city+"\"}}]");

然后您生成的JSON将有效

{
    "venue_queries": "[{\"name\":\"yo\", \"location\": {\"locality\": \"Solares\"}}]",
    "api_key": "asfasdfasfdasdfasdfa"
}

Tes片段

import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

import com.google.gson.Gson;

public class GsonMap {

    public static void main(String[] args) {
        Map<String, String> map = new HashMap<String, String>();
        String apikey = "asfasdfasfdasdfasdfa";
        map.put("api_key", apikey);
        String name = "yo";
        String city = "Solares";
        map.put("venue_queries", "[{\"name\":\""+name+"\", \"location\": {\"locality\": \""+city+"\"}}]");
        Gson gson = new Gson();
        String json = gson.toJson(map);
        System.out.println("Resulting JSON:" + json);
        map = gson.fromJson(json, map.getClass());
        System.out.println("Resulting map values:");
        for (Entry<String, String> entry : map.entrySet()) {
            System.out.println("Key:" + entry.getKey() + ", value:" + entry.getValue());
        }
    }
}