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);
}
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
Related
In JsnoToApex class I try to GET JSON file from https://openweathermap.org/current. When I try to parse JSON.CreateParses I get these error: Illegal assignment from System.JSONParser to JsonParser
I try to make API that show weather in London.
public with sharing class JsonToApex {
#future(callout=true)
public static void parseJSONResponse() {
String resp;
Http httpProtocol = new Http();
// Create HTTP request to send.
HttpRequest request = new HttpRequest();
// Set the endpoint URL.
String endpoint = 'https://samples.openweathermap.org/data/2.5/weather?q=London,uk&appid=b6907d289e10d714a6e88b30761fae22';
request.setEndPoint(endpoint);
// Set the HTTP verb to GET.
request.setMethod('GET');
// Send the HTTP request and get the response.
// The response is in JSON format.
HttpResponse response = httpProtocol.send(request);
resp = response.getBody();
JSONParser parser = JSON.createParser(resp);
JsonMapper response = (JsonMapper) System.JSON.deserialize(res.getBody(), JsonMapper.class);
}
}
I expect to get Json file and in future map it using https://json2apex.herokuapp.com/
The problem was in first JSONParser. I had to add System.JSONParser to make it work.
System.JSONParser parser = JSON.createParser(resp);
You may have two approaches:
If you have already map the JSON into an Apex class, you may just use
JSON2Apex aClass = (JSON2Apex) System.JSON.deserialize(resp, JSON2Apex.class);
Where JSON2Apex is the mapping Apex class.
Use the JSON.deserializeUntyped(String jsonString) to deserialize the JSON to any Object in Apex class, like:
Map<String, Object> objMap = (Map<String, Object>) JSON.deserializeUntyped(resp);
I want to read JSON response coming from jenkins API to read last build details. I am using http://jenkins_server/job/job_name/lastBuild/api/json. When I type this URL in browser, I need to sign in to my Jenkins job and after that I get proper json response.
I have written a java code to read JSON response from same Jenkins API. But I get "Server returned HTTP response code: 403" as I have not handled the authentication part in code.
public class GetJSONResponse {
public static void main(String[] args) throws MalformedURLException, IOException, JSONException {
InputStream is = new URL("http://jenkins_server/job/job_name/lastBuild/api/json").openStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
StringBuilder sb = new StringBuilder();
int cp;
while ((cp = rd.read()) != -1) {
sb.append((char) cp);
}
JSONObject json = new JSONObject(sb.toString());
System.out.println(json.toString());
}
}
I searched alot on how to get JSON response from jenkins API which reqiures authentication , but didn't find anything useful. How do I add authentication part in my code? Can anybody please help me with this?
Thanks in advance.
I resolved my problem after changing the jenkins config.xml "useSecurity" fileld.
Change <useSecurity>true</useSecurity> to <useSecurity>false</useSecurity>
And I got correct JSON response.
I was using Jersey 1.16 to consume a JSON, but now I'm with difficulties to consume a JSON using Jersey 2.0 (that implements JAX-RS 2.0).
I have a JSON response like this:
{
"id": 105430,
"version": 0,
"cpf": "55443946447",
"email": "maria#teste.br",
"name": "Maria",
}
and the method that consumes it:
public static JSONObject get() {
String url = "http://127.0.0.1:8080/core/api/person";
URI uri = URI.create(url);
final Client client = ClientBuilder.newClient();
WebTarget webTarget = client.target(uri);
Response response = webTarget.request(MediaType.APPLICATION_JSON).get();
if (response.getStatus() == 200) {
return response.readEntity(JSONObject.class);
}
}
I also tried:
return webTarget.request(MediaType.APPLICATION_JSON).get(JSONObject.class);
But the jSONObject return is null. I don't understand my error because the response is OK!
This is how to use the Response type correctly:
private void getRequest() {
Client client = ClientBuilder.newClient();
String url = "http://localhost:8080/api/masterdataattributes";
WebTarget target = client.target(url);
Response res = target
.request(MediaType.APPLICATION_JSON)
.get();
int status = res.getStatus();
String json = res.readEntity(String.class);
System.out.println(String.format("Status: %d, JSON Payload: %s", status, json));
}
If you're just interested in the payload, you could also just issue a get(String.class). But usually you will also want to check the response status, so working with the Response is usually the way to go.
If you want a typed (generic) JSON response, you could also have readEntity return a Map, or a list of Map if the response is an array of objects as in this example:
List<Map<String, Object>> json = res.readEntity(new GenericType<List<Map<String, Object>>>() {});
String id = (String) json.get(0).get("id");
System.out.println(id);
I have found the solution. Maybe it is not the best of, but it works.
public static JsonObject get() {
String url = "http://127.0.0.1:8080/core/api/person";
URI uri = URI.create(url);
final Client client = ClientBuilder.newClient();
WebTarget webTarget = client.target(uri);
Response response = webTarget.request(MediaType.APPLICATION_JSON).get();
//Se Response.Status.OK;
if (response.getStatus() == 200) {
StringReader stringReader = new StringReader(webTarget.request(MediaType.APPLICATION_JSON).get(String.class));
try (JsonReader jsonReader = Json.createReader(stringReader)) {
return jsonReader.readObject();
}
}
return null;
}
I switched the class JSONObject (package import org.codehaus.jettison) by JsonObject (package javax.json) and I used the methods to manipulate the content as String.
S.
mmey answer is the correct and optimal one, instead of invoking the service twice it does it one time.
I'm using apache httpcompnonents library for httpclient. I want to use it in a multithreaded application where number of threads are going to be really high and there would be frequent http calls. This is the code I'm using to read the response after execute call.
HttpEntity entity = httpResponse.getEntity();
String response = EntityUtils.toString(entity);
I just want to confirm that is it the most efficient way of reading the response?
Thanks,
Hemant
This in fact represents the most inefficient way of processing an HTTP response.
You most likely want to digest the content of the response into a domain object of a sort. So, what is the point of buffering it in-memory in a form of a string?
The recommended way to deal with response processing is by using a custom ResponseHandler that can process the content by streaming it directly from the underlying connection. The added benefit of using a ResponseHandler is that it completely relieves from dealing with connection release and resource deallocation.
EDIT: modified the sample code to use JSON
Here's an example of it using HttpClient 4.2 and Jackson JSON processor. Stuff is assumed to be your domain object with JSON bindings.
ResponseHandler<Stuff> rh = new ResponseHandler<Stuff>() {
#Override
public Stuff handleResponse(
final HttpResponse response) throws IOException {
StatusLine statusLine = response.getStatusLine();
if (statusLine.getStatusCode() >= 300) {
throw new HttpResponseException(
statusLine.getStatusCode(),
statusLine.getReasonPhrase());
}
HttpEntity entity = response.getEntity();
if (entity == null) {
throw new ClientProtocolException("Response contains no content");
}
JsonFactory jsonf = new JsonFactory();
InputStream instream = entity.getContent();
// try - finally is not strictly necessary here
// but is a good practice
try {
JsonParser jsonParser = jsonf.createParser(instream);
// Use the parser to deserialize the object from the content stream
return stuff;
} finally {
instream.close();
}
}
};
DefaultHttpClient client = new DefaultHttpClient();
Stuff mystuff = client.execute(new HttpGet("http://somehost/stuff"), rh);
I am writing code that needs to extract an object literal posted to a servlet. I have studied the API for the HttpServletRequest object, but it is not clear to me how to get the JSON object out of the request since it is not posted from a form element on a web page.
Any insight is appreciated.
Thanks.
are you looking for this ?
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
StringBuilder sb = new StringBuilder();
BufferedReader reader = request.getReader();
try {
String line;
while ((line = reader.readLine()) != null) {
sb.append(line).append('\n');
}
} finally {
reader.close();
}
System.out.println(sb.toString());
}
This is simple method to get request data from HttpServletRequest
using Java 8 Stream API:
String requestData = request.getReader().lines().collect(Collectors.joining());
make use of the jackson JSON processor
ObjectMapper mapper = new ObjectMapper();
Book book = mapper.readValue(request.getInputStream(),Book.class);
The easiest way is to populate your bean would be from a Reader object, this can be done in a single call:
BufferedReader reader = request.getReader();
Gson gson = new Gson();
MyBean myBean = gson.fromJson(reader, MyBean.class);
There is another way to do it, using org.apache.commons.io.IOUtils to extract the String from the request
String jsonString = IOUtils.toString(request.getInputStream());
Then you can do whatever you want, convert it to JSON or other object with Gson, etc.
JSONObject json = new JSONObject(jsonString);
MyObject myObject = new Gson().fromJson(jsonString, MyObject.class);
If you're trying to get data out of the request body, the code above works. But, I think you are having the same problem I was..
If the data in the body is in JSON form, and you want it as a Java object, you'll need to parse it yourself, or use a library like google-gson to handle it for you. You should look at the docs and examples at the project's website to know how to use it. It's fairly simple.
Converting the retreived data from the request object to json object is as below using google-gson
Gson gson = new Gson();
ABCClass c1 = gson.fromJson(data, ABCClass.class);
//ABC class is a class whose strcuture matches to the data variable retrieved