0

我正在尝试用java发送这个:

curl -H "Content-Type:application/json" -XPOST 'http://www.example.com/foo' -d '{"rootURL": "http://www.subway.com"}'

这是我的代码:

    HttpClient client = new DefaultHttpClient();
    HttpPost post = new HttpPost("http://www.example.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);

但我收到 400 错误:

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]

如果我改变这一行:

urlParameters.add(new BasicNameValuePair("rootURL", "http://www.subway.com"));

urlParameters.add(new BasicNameValuePair("bootURL", "http://www.subway.com"));

我收到以下错误:

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]

有谁知道问题是什么?

4

1 回答 1

0

出于某种原因,如果我更换它会起作用:

List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
urlParameters.add(new BasicNameValuePair("rootURL", "http://www.subway.com"));
post.setEntity(new UrlEncodedFormEntity(urlParameters));

和:

post.setEntity(new StringEntity("{\"rootURL\":\"http://www.subway.com\"}", "UTF-8"));

这是我从中找到此建议的链接,但它没有回答原因。谁能解释为什么它不能与 UrlEncodedFormEntity 一起使用?

Android:带有参数的 Http 帖子不起作用

于 2013-07-25T20:51:15.153 回答