简体   繁体   English

如何将此 curl 请求转换为 Apache HttpClient java 代码?

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

I'm trying to send this in java:我想用java发送这个:

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

Here's the code I have:这是我的代码:

    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);

but I'm getting a 400 error:但我收到 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]

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?有谁知道问题是什么?

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?谁能解释为什么它不能与 UrlEncodedFormEntity 一起使用?

Android: Http post with parameters not working Android:带参数的 Http 帖子不起作用

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM