我正在尝试将POST参数发送到我拥有的REST端点。这个参数是一个JSON字符串,它包含特殊的字符,如双引号(“)。在端点上,我继续对字符串进行编码。
这是请求部分:
HttpClient client = HttpClientBuilder.create().build();
StringBuilder query = new StringBuilder();
query.append(callBackURL);
ArrayList<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
urlParameters.add(new BasicNameValuePair("update", "{\"object\":\"page\",\"entry\":[{\"id\":\"316492991876763\",\"time\":1417436403,\"changes\":[{\"field\":\"feed\",\"value\":{\"item\":\"comment\",\"verb\":\"add\",\"comment_id\":\"321528008039928_323256911200371\",\"parent_id\":\"316492991876763_321528008039928\",\"sender_id\":100006737955082,\"created_time\":1417436403}}]}]}"));
try {
HttpPost post = new HttpPost(query.toString());
post.setEntity(new UrlEncodedFormEntity(urlParameters));
post.addHeader("content-type", "application/json");
HttpResponse response = null;
try {
response = client.execute(post);
}
catch (IOException e) {
System.out.println(e.getMessage());
}
}
catch (UnsupportedEncodingException e2) {
System.out.println(e2.getMessage());
}
现在在端点部分:
/**
* Callback method that receives FB updates
* @return 200 OK if everything goes OK, 401 ERROR otherwise
*/
@POST
@Path("/callback")
@Consumes(MediaType.APPLICATION_JSON)
public Response facebookUpdate(String update, @Context HttpServletRequest request, @Context HttpServletResponse response) throws ServletException, IOException{
JsonParser jsonParser = new JsonParser();
//parse it
JsonElement json = jsonParser.parse(update);
...
}
我得到的是一个像这样编码的字符串:
%7B%22object%22%3A%22page%22%2C%22entry%22%3A%5B%7B%22id%22%3A%22316492991876763%22%2C%22time%22%3A1417436403%2C%22changes%22%3A%5B%7B%22field%22%3A%22feed%22%2C%22value%22%3A%7B%22item%22%3A%22comment%22%2C%22verb%22%3A%22add%22%2C%22comment_id%22%3A%22321528008039928_323256911200371%22%2C%22parent_id%22%3A%22316492991876763_321528008039928%22%2C%22sender_id%22%3A100006737955082%2C%22created_time%22%3A1417436403%7D%7D%5D%7D%5D%7D
我无法将其转换为JsonElement ......
任何想法如何避免这种情况?
谢谢! 亚历
更新
我发现了问题所在,所以我在这里解释,以防有人遇到同样的问题。
我试图使用BasicNameValuePair传递一个参数,如下所示:
ArrayList<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
urlParameters.add(new BasicNameValuePair("update", "{\"object\":\"page\",\"entry\":[{\"id\":\"316492991876763\",\"time\":1417436403,\"changes\":[{\"field\":\"feed\",\"value\":{\"item\":\"comment\",\"verb\":\"add\",\"comment_id\":\"321528008039928_323256911200371\",\"parent_id\":\"316492991876763_321528008039928\",\"sender_id\":100006737955082,\"created_time\":1417436403}}]}]}"));
我已经改为简单的StringEntity,如下所示:
StringEntity params = new StringEntity(json.toString());
HttpPost post = new HttpPost(query.toString());
因此,我不需要解码。为什么传递一个BasicNameValuePair数组会对String ...
进行编码仍然存在问题答案 0 :(得分:0)
在要从
生成JSON的方法上方使用注释@Produces("application/json")