Java 使用 spring 中的 rest 模板通过 post 调用发送 json 数据
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22856594/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
send json data through a post call by using rest template from spring
提问by РАВИ
I keep getting an error saying that this is not valid json data and keep getting error 400. I don't think the implementation I have is formatting data properly. Goal: trying to make a post call using a rest template, by passing in JSON data as the body. It seems that when converting from map to json data, it isn't properly converted to json.
我不断收到错误消息,说这不是有效的 json 数据,并不断收到错误 400。我认为我的实现没有正确格式化数据。目标:通过将 JSON 数据作为正文传入,尝试使用 rest 模板进行后期调用。似乎在从 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 MappingHymanson2HttpMessageConverter());
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";
}
}
采纳答案by vzamanillo
Right, your resulting JSON is not valid
是的,您生成的 JSON 无效
{
"venue_queries": "[{\u0027name\u0027:\u0027yo\u0027, \u0027location\u0027: {\u0027locality\u0027: \u0027Solares\u0027}}]",
"api_key": "asfasdfasfdasdfasdfa"
}
you JSON is not valid because GSON escapes the HTML characters by default and put the single quotes as the equivalent unicode char code U+0027
您的 JSON 无效,因为 GSON 默认情况下会转义 HTML 字符并将单引号作为等效的 Unicode 字符代码 U+0027
if you disable the Gson HTMLEscaping
如果您禁用Gson HTMLEscaping
GsonBuilder builder = new GsonBuilder();
builder.disableHtmlEscaping();
Gson gson = builder.create();
you will get
你会得到
{
"venue_queries": "[{'name':'yo', 'location': {'locality': 'Solares'}}]",
"api_key": "asfasdfasfdasdfasdfa"
}
anyway, your JSON is still incorrect.
无论如何,您的 JSON 仍然不正确。
You have to fix your venue_queries
key content int the map using double quotes
"
您必须venue_queries
在地图中修复您的关键内容using double quotes
"
map.put("venue_queries", "[{\"name\":\""+name+"\", \"location\": {\"locality\": \""+city+"\"}}]");
then your resulting JSON will be valid
那么您生成的 JSON 将是有效的
{
"venue_queries": "[{\"name\":\"yo\", \"location\": {\"locality\": \"Solares\"}}]",
"api_key": "asfasdfasfdasdfasdfa"
}
Tes snippet
测试片段
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());
}
}
}