我如何把这个卷曲要求到Apache的HttpClient的java code? [英] How do I convert this curl request to Apache HttpClient java code?

查看:202
本文介绍了我如何把这个卷曲要求到Apache的HttpClient的java code?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在java中发送此:

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"}'

这里的code我有:

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

但我得到一个400错误:

but I'm getting a 400 error:

意外的字符('R'(code 98)):期待一个有效的值(数字,字符串,数组,对象,'真','假'或'空')在[来源:org.apache .catalina.connector.CoyoteInputStream @ a18ba7b;行:1,列:2]

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

我收到以下错误:

I get the following error:

意外的字符('B'(code 98)):期待一个有效的值(数字,字符串,数组,对象,'真','假'或'空')在[来源:org.apache .catalina.connector.CoyoteInputStream @ a18ba7b;行:1,列:2]

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]

有谁知道问题是什么?

推荐答案

由于某种原因,如果我更换工作:

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

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

下面是我发现从这个建议的联系,但它不回答为什么。任何人都可以解释为什么它不会与UrlEn codedFormEntity工作?

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?

<一个href=\"http://stackoverflow.com/questions/5958182/android-http-post-with-parameters-not-working\">Android: HTTP POST使用参数不工作

这篇关于我如何把这个卷曲要求到Apache的HttpClient的java code?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆