【问题标题】:how to include the json file in request body using httpClient?如何使用 httpClient 在请求正文中包含 json 文件?
【发布时间】:2016-02-25 07:14:19
【问题描述】:

如何使用 httpClient 在请求正文中包含 json 文件? 我的 Json:

{
    "products": {
        "product": {
            "sku": "100",
            "varientsku": "0",
            "mrp": "5,300",
            "webprice": "5,220",
            ”inventory”: ”25”
        }
    }
}

我的代码:

public static void main(String args[])

{

uri=//url

JSONObject json=new JSONObject();

json.put("sku", "100");

json.put("mrp", "12121");

json.put("inventory", "2525");

JSONObject product=new JSONObject();

product.put("product", json);

JSONObject products=new JSONObject();

products.put("products", product);

HttpPost postRequest=new HttpPost(uri);

postRequest.addHeader("accept", "application/json");

postRequest.setHeader("ContentType", "application/json");

postRequest.setEntity(new StringEntity(products.toString(), "UTF-8"));

HttpResponse response=httpClient.execute(postRequest);

}

【问题讨论】:

  • 你能提供一些上下文吗?到目前为止,您尝试过什么?
  • 感谢您的回复 mithrandir,请尽快提供答案

标签: json http http-post


【解决方案1】:

将文件读入内存并对其进行json_encode。

在javascript中:

 var json = JSON.stringify(file);

在 C# 中:

var serializer = new JavaScriptSerializer();
string json = serializer.Serialize(file);

那么你所拥有的是一个包含文件中所有信息的字符串。像传递任何字符串信息一样传递它。那么当你处理它时(大概是在php中?),json_decode它,

$jsonObject = json_encode($data['body']);

我希望这对您的问题有所帮助。如果没有,请提供更多信息,例如您使用的语言以及您使用 httpClient 的目的。信息越多越好。

~~应要求更新~~

对于 Java,似乎人们推荐使用 Apache 的 HttpClient 库发现:HERE,请查看教程的前几章,看看它是否是您想要的。您也可以在该站点上从他们那里下载库。

对于简单的请求,有些人会使用oracle的HttpURLconnection(找到HERE)例子:

URL url = new URL("http://example.com");
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("GET");
connection.connect();

InputStream stream = connection.getInputStream(); //read the contents using an InputStreamReader

我找到了这个信息HERE

【讨论】:

  • 能否请您用java语言提供详细信息。我正在使用httpclient执行post请求
猜你喜欢
  • 2019-08-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-08-13
  • 1970-01-01
  • 1970-01-01
  • 2012-01-16
  • 1970-01-01
相关资源
最近更新 更多