How to POST JSON with Jersey WebResource.Builder? - java

I wanna POST a JSONOject or a Map using a Jersey Client with a WebSresource.Builder.
WebResource.Builder builder = res.type(mediaType);
uploadResult = builder.post(ClientResponse.class, new HashMap<String, Object>());
How do I pass the JSON the right way to the POSt request? How the JSON/Map has to be converted?
//cheers

Related

Walmart (Java integration)- post feed with Resttemplate

I'm currently integrating Walmart into our application and I'm trying to post an Item Feed through the API method.
I've already succeeded in posting a feed from the ARC tool, so I already know how to model the post request for it, my only problem is that I'm having difficulties in using it in my code, while using the Resttemplate.
Below is the request (from ARC - Chrome) that succeeded to post my item (I can see them in my Walmart Seller console) and the Java code for it (trimmed the credentials for security reason):
Obs: The signature and the other fields used in the Java code for the requests are correctly generated, because I used them in my request from ARC as well, so there's no issue in the headers' values, but in how I'm trying to set the file in the body request, as far as I can tell:
And the code for generating the headers and sending the post request with Resttemplate:
..............................
headers = new HttpHeaders();
headers.set("WM_SVC.NAME", "Walmart Marketplace");
headers.set("WM_QOS.CORRELATION_ID", "123456abcdef");
headers.set("WM_SEC.TIMESTAMP", timestamp);
headers.set("WM_SEC.AUTH_SIGNATURE", signatureString);
headers.set("WM_CONSUMER.ID", "my-consumer-id-cut-for-security-reasons");
headers.set("WM_CONSUMER.CHANNEL.TYPE", "my-channel-type");
headers.setContentType(MediaType.MULTIPART_FORM_DATA);
headers.setAccept(Arrays.asList(MediaType.APPLICATION_XML));
headers.set("Host", "https://marketplace.walmartapis.com");
..............................
File file = new File("C:\\walmartfeed.xml");
DiskFileItem fileItem = new DiskFileItem("file", "text/xml", false, file.getName(), (int) file.length(), file.getParentFile());
fileItem.getOutputStream();
MultipartFile multipartFile = new CommonsMultipartFile(fileItem);
MultiValueMap<String, Object> parts =
new LinkedMultiValueMap<String, Object>();
parts.add("file", new ByteArrayResource(multipartFile.getBytes()));
HttpEntity<MultiValueMap<String, Object>> request = new HttpEntity<>(parts, headers);
restTemplate.getMessageConverters().add(new FormHttpMessageConverter());
restTemplate.getMessageConverters().add(new ByteArrayHttpMessageConverter());
restTemplate.getMessageConverters().add(new MultipartAwareFormHttpMessageConverter());
ResponseEntity<FeedAcknowledgement> response = restTemplate.exchange("https://marketplace.walmartapis.com/v3/feeds?feedType=item", org.springframework.http.HttpMethod.POST, request, FeedAcknowledgement.class);
I am receiving a 400 status code saying it's a bad request.
Did you manage to post feeds for Walmart or is there any other way to use Resttemplate to post multipart/form-data / files ?
Thanks

Saving data from url to JSON object

I have to create JSON parser to save data received from url into JSON object using org.json library and only java standard libraries but I have no idea how to connec to those
String line = "326";
URL oracle = new URL("https://api.tfl.gov.uk/Line/"+line+"/Arrivals?app_id=&app_key=");
BufferedReader in = new BufferedReader(
new InputStreamReader(oracle.openStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
System.out.println(inputLine);
in.close();
This my connection code
My suggestion would be to use a JSON parser such as Jackson.
Create a class that would store the data you want to store from
that JSON.
Use URL to connect and grab the JSON
Use Jackson to convert it to a Java object
Let me know if you need more help and I can provide it.
Use an http client library like okhttp to make the request and get the string body.
Then use a json parser like Jackson to parse the received string into Json object.
Use okhttp as below:
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(url)
.build();
Response resp = client.newCall(request).execute();
String response = resp.body().string();
Once you have the response string you can make a jsonNode from it by using Jackson ObjectMapper as below
ObjectMapper mapper = new ObjectMapper();
JsonNode tree = mapper.readTree(response);
Or get your defined POJO by parsing the response as
YourClass mappedPOJO = mapper.readValue(response, YourClass.class);
Lets say your incoming json was
{
"key1":"value1",
"key2": {
"key3":"value3"
}
}
Then tree.get("key1") gives you "value1",
tree.get("key1").get("key2") gives you "value3"

PHP RESTful API accessing Jersey Client POST data

I am using a PHP RESTful API which is consumed by a Java desktop application using jersey 2.21.
Usually, when I send a POST request from AngularJS, I can access the data via:
$data = json_decode(file_get_contents("php://input"));
However, when I use jersey, the data is put in the $_POST array. Here is my Jersey code:
final HashMap<String, String> params = // some hashmap with a few entries
ClientConfig config = new ClientConfig();
Client client = ClientBuilder.newClient(config);
MultivaluedMap formData = new MultivaluedHashMap(params);
WebTarget target = client.target(url);
// Get JSON
String jsonResponse = target.request(MediaType.APPLICATION_JSON_TYPE).post(Entity.entity(formData, MediaType.APPLICATION_FORM_URLENCODED_TYPE), String.class);
return jsonResponse;
How do I post the data from Jersey so that I can access it via the above PHP call?
I know I can just use the $_POST array, but I need this API to be consumed from a mobile app, Java desktop & an AngularJS app.
Thanks in advance
Thanks to #jonstirling, I got it.
I had to set the content type as JSON. here is the updated code:
ClientConfig config = new ClientConfig();
Client client = ClientBuilder.newClient(config);
WebTarget target = client.target(url);
String data = new Gson().toJson(params);
// POST JSON
Entity json = Entity.entity(data, MediaType.APPLICATION_JSON_TYPE);
Invocation.Builder builder = target.request(MediaType.APPLICATION_JSON_TYPE);
String jsonResponse = builder.post(json, String.class);
return jsonResponse;

Updating multiple fields for an Object - Dynamics CRM 2011 using java

Is there any way to update multiple fields for an object in Dynamics CRM 2011 using java. All I am able to do now is to update one field for an object (ContactSet,AccountSet etc..)
URL : https://xxxxxx.xxxx.xx/xxxxxx/XrmServices/2011/OrganizationData.svc/ContactSet(guid'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx')
What I have done?
Map<String,Object> update = Maps.newHashMap();
update.put("FirstName","xxxxx");
update.put("LastName","xxxxx");
update.put("Telephone1","xxxxxxxx");
ObjectMapper mMapper = new ObjectMapper();
mEntity = mMapper.writeValueAsString(update);
String mUrl = this.url+"/"+getObject()+"(guid'"+id+"')";
HttpPut httpPut = new HttpPut(mUrl);
httpPut.setHeader("Content-Type", "application/json");
httpPut.setHeader("Accept","application/json");
httpPut.setEntity(new StringEntity(mEntity,"UTF-8"));
HttpResponse response = this.client.execute(httpPut);
The above code always gives a 500 internal server error.
What works?
Map<String,Object> update = Maps.newHashMap();
update.put("FirstName","xxxxx");
mEntity = mMapper.writeValueAsString(update);
String mUrl = this.url+"/"+getObject()+"(guid'"+id+"')"+"/FirstName";
HttpPut httpPut = new HttpPut(mUrl);
httpPut.setHeader("Content-Type", "application/json");
httpPut.setHeader("Accept","application/json");
httpPut.setEntity(new StringEntity(mEntity,"UTF-8"));
HttpResponse response = this.client.execute(httpPut);
I don't see a point in updating just a single field. Can someone please give pointers on how to update multiple fields?
I would recommend you to use javascript and Jquery or if you prefer java try to follow the microsoft code Javascript example.
It is possible to update multiple columns, just check your code syntax.

Using the Jersey client to do a POST operation

In a Java method, I'd like to use a Jersey client object to do a POST operation on a RESTful web service (also written using Jersey) but am not sure how to use the client to send the values that will be used as FormParam's on the server. I'm able to send query params just fine.
Not done this yet myself, but a quick bit of Google-Fu reveals a tech tip on blogs.oracle.com with examples of exactly what you ask for.
Example taken from the blog post:
MultivaluedMap formData = new MultivaluedMapImpl();
formData.add("name1", "val1");
formData.add("name2", "val2");
ClientResponse response = webResource
.type(MediaType.APPLICATION_FORM_URLENCODED_TYPE)
.post(ClientResponse.class, formData);
That any help?
Starting from Jersey 2.x, the MultivaluedMapImpl class is replaced by MultivaluedHashMap. You can use it to add form data and send it to the server:
WebTarget webTarget = client.target("http://www.example.com/some/resource");
MultivaluedMap<String, String> formData = new MultivaluedHashMap<String, String>();
formData.add("key1", "value1");
formData.add("key2", "value2");
Response response = webTarget.request().post(Entity.form(formData));
Note that the form entity is sent in the format of "application/x-www-form-urlencoded".
It is now the first example in the Jersey Client documentation
Example 5.1. POST request with form parameters
Client client = ClientBuilder.newClient();
WebTarget target = client.target("http://localhost:9998").path("resource");
Form form = new Form();
form.param("x", "foo");
form.param("y", "bar");
MyJAXBBean bean =
target.request(MediaType.APPLICATION_JSON_TYPE)
.post(Entity.entity(form,MediaType.APPLICATION_FORM_URLENCODED_TYPE),
MyJAXBBean.class);
If you need to do a file upload, you'll need to use MediaType.MULTIPART_FORM_DATA_TYPE.
Looks like MultivaluedMap cannot be used with that so here's a solution with FormDataMultiPart.
InputStream stream = getClass().getClassLoader().getResourceAsStream(fileNameToUpload);
FormDataMultiPart part = new FormDataMultiPart();
part.field("String_key", "String_value");
part.field("fileToUpload", stream, MediaType.TEXT_PLAIN_TYPE);
String response = WebResource.type(MediaType.MULTIPART_FORM_DATA_TYPE).post(String.class, part);
Simplest:
Form form = new Form();
form.add("id", "1");
form.add("name", "supercobra");
ClientResponse response = webResource
.type(MediaType.APPLICATION_FORM_URLENCODED_TYPE)
.post(ClientResponse.class, form);
Also you can try this:
MultivaluedMap formData = new MultivaluedMapImpl();
formData.add("name1", "val1");
formData.add("name2", "val2");
webResource.path("yourJerseysPathPost").queryParams(formData).post();

Categories

Resources