0

how to include the json file in request body using httpClient? My Json:

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

My code:

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

}
Sandeep
  • 1,504
  • 7
  • 22
  • 32

1 Answers1

0

Read the file into memory and json_encode it.

in javascript:

 var json = JSON.stringify(file);

in c#:

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

Then what you have is a string with all the information in the file. Pass it as you would any string information. Then when you handle it (presumably in php?), json_decode it,

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

I hope this helps with your question. If not, please provide more information like what language you are using, and for what purpose you are using httpClient. The more information, the better.

~~UPDATED UPON REQUEST~~

For Java, it appears that people recommend using Apache's HttpClient library found: HERE, look at the first few chapters of the tutorial to see if it's what you want. You can download the library from them on that site as well.

For simple requests, some people will use HttpURLconnection by oracle (found HERE) example:

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

I found this information HERE

Community
  • 1
  • 1
JohnGalt
  • 61
  • 6