How do I convert this curl request to Apache HttpClient java code?

爷,独闯天下 提交于 2019-12-12 03:13:45

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!