问题
I'm trying to send this in java:
curl -H "Content-Type:application/json" -XPOST 'http://www.foo.com/foo' -d '{"rootURL": "http://www.subway.com"}'
Here's the code I have:
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("http://www.foo.com/foo");
post.setHeader("Content-Type", "application/json");
List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
urlParameters.add(new BasicNameValuePair("rootURL", "http://www.subway.com"));
post.setEntity(new UrlEncodedFormEntity(urlParameters));
client.execute(post);
but I'm getting a 400 error:
Unexpected character ('r' (code 98)): expected a valid value (number, String, array, object, 'true', 'false' or 'null') at [Source: org.apache.catalina.connector.CoyoteInputStream@a18ba7b; line: 1, column: 2]
If I change this line:
urlParameters.add(new BasicNameValuePair("rootURL", "http://www.subway.com"));
to
urlParameters.add(new BasicNameValuePair("bootURL", "http://www.subway.com"));
I get the following error:
Unexpected character ('b' (code 98)): expected a valid value (number, String, array, object, 'true', 'false' or 'null') at [Source: org.apache.catalina.connector.CoyoteInputStream@a18ba7b; line: 1, column: 2]
Does anyone know what the problem is?
回答1:
for some reason it works if I replace:
List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
urlParameters.add(new BasicNameValuePair("rootURL", "http://www.subway.com"));
post.setEntity(new UrlEncodedFormEntity(urlParameters));
with:
post.setEntity(new StringEntity("{\"rootURL\":\"http://www.subway.com\"}", "UTF-8"));
Here's the link I found this suggestion from, but it doesn't answer why. Can anyone explain why it won't work with UrlEncodedFormEntity?
Android: Http post with parameters not working
来源:https://stackoverflow.com/questions/17868189/how-do-i-convert-this-curl-request-to-apache-httpclient-java-code