I need to send a JSON body to https://mandrillapp.com/api/1.0//messages/send-template.json . How do I do this using RestEasy in Java? This is what I have so far:
ResteasyClient client = new ResteasyClientBuilder().build();
ResteasyWebTarget target = client.target("https://mandrillapp.com/api/1.0//messages/send-template.json");
How do I actually send the JSON?
Once you have the ResteasyWebTarget, you need to get the Invocation
Invocation.Builder invocationBuilder = target.request("text/plain").header("some", "header");
Invocation incovation = invocationBuilder.buildPost(someEntity);
invocation.invoke();
where someEntity is some instance of Entity<?>. Create one with
Entity<String> someEntity = Entity.entity(someJsonString, MediaType.APPLICATION_JSON);
Read this javadoc.
This is for 3.0 beta 4.
This is a bit old question, but I found it looking for something similar on Google, so this is my solution, using RestEasy client 3.0.16:
I'll use a Map object to be sent but you can use whatever JavaBean that Jackson provider can convert to JSON.
BTW, you'll need add as dependency the resteasy-jackson2-provider lib.
ResteasyClient client = new ResteasyClientBuilder().build();
ResteasyWebTarget target = client.target("http://server:port/api/service1");
Map<String, Object> data = new HashMap<>();
data.put("field1", "this is a test");
data.put("num_field2", 125);
Response r = target.request().post( Entity.entity(data, MediaType.APPLICATION_JSON));
if (r.getStatus() == 200) {
// Ok
} else {
// Error on request
System.err.println("Error, response: " + r.getStatus() + " - "+ r.getStatusInfo().getReasonPhrase());
}
I've never used this framework, but according to an example at this url, you should be able to make a call like this:
Client client = ClientBuilder.newBuilder().build();
WebTarget target = client.target("http://foo.com/resource");
Response response = target.request().get();
String value = response.readEntity(String.class);
response.close(); // You should close connections!
The 3rd line seems to be the answer you're looking for.
Related
Hi i have written a rest service to delete multiple files and i am trying to access the rest service.
My input to rest service will be List values which will be id of files that needs to be deleted.
For that i have written the below code
List<Long> ids=new ArrayList<Long>();
ids.add(4l);
ids.add(5l);
boolean status = false;
String jsonResponse = null;
DefaultHttpClient httpClient = null;
HttpResponse response = null;
try {
httpClient = new DefaultHttpClient();
StringBuilder url = new StringBuilder("http://localhost:8080/api/files");
URIBuilder builder = new URIBuilder();
URI uri = builder.build();
HttpDelete deleteRequest = new HttpDelete(uri);
//how to set list as Requestbody and send
response = httpClient.execute(deleteRequest);
}
Here i dont know how to set List as entity in request body and send. Can someone help me on this
A HTTP DELETE request should delete the resource identified by the URI. The body is not relevant. To delete a single resource:
DELETE /api/files/123
If you want to delete more than one file in a single request, model a collection of files as a resource. This could be done by listing more than one ID in the URL:
GET /api/files/123,456,789
This could return a JSON array with the details of the three files.
To delete these three files, execute a DELETE request agains the same URL:
DELETE /api/files/123,456,789
I've found several examples of how to consume multipart POSTs to Jersey, but not how to produce this format.
I'm in the process of translating an Apache Wink web service to Apache Jersey (2.25). Both are JAX-RS 2, but I've found some special constructs that exist in Wink that are a challenge to find equivalents for in Jersey.
Since the API is essentially a contract between my service and existing clients, I want to return the same format with Jersey that the service returns now.
The Wink method looks like this (I tried to simplify it a bit):
#POST
#Path("download")
#Consumes({MediaType.APPLICATION_JSON, ApiConstants.MEDIA_TEXT_XML_UTF8,
ApiConstants.MEDIA_APPLICATION_XML_UTF8})
#Produces({MediaType.MULTIPART_FORM_DATA})
public Response getFiles(#Context HttpHeaders httpHeaders, MyFileManifest manifest)
throws IOException, PermissionDeniedException {
String boundary = "boundary-" + UUID.randomUUID().toString();
// ... Creates this Wink construct ...
BufferedOutMultiPart mpEntity = new BufferedOutMultiPart();
for (int i = 0; i < manifest.getFiles().size(); ++i) {
MyManifestEntry entry = manifest.getFiles().get(i);
OutPart op = new OutPart();
op.addHeader("Name", "file-" + Integer.toString(entryIndex));
String disposition = "file; filename=\"" + content.partialPath.replace("\"", "\"\"") + "\"";
op.addHeader("Content-Disposition", disposition);
op.addHeader("Content-Type", content.contentType);
op.setBody(fileBlob);
mpEntity.addPart(op);
}
ResponseBuilder rBuild = Response.status(Status.OK).entity(mpEntity)
.header(ApiConstants.OPEN_DATA_KIT_VERSION_HEADER, ApiConstants.OPEN_DATA_KIT_VERSION)
.header("Access-Control-Allow-Origin", "*")
.header("Access-Control-Allow-Credentials", "true");
return rBuild.build();
}
How can I do this with Jersey? I found the documentation for the Jersey FormDataMultiPart class but it doesn't sound like it is intended for returning data.
I'm using Jersey 2.22. My code:
WebTarget target = ClientBuilder.newClient().target("https://api.someurl.com");
MultivaluedMap<String, String> map = new MultivaluedHashMap<>();
map.add("param1", "1");
map.add("param2", "2");
map.add("param3", "3");
Response response = target.request().post(Entity.form(map));
This works well, however, I want to include an image and I have no idea how to do it. I've read the documentation and couldn't find how to do it.
So, I found out that a jersey-media-multipart module existed. I added it to my dependencies and changed my code to:
Client client = ClientBuilder.newClient();
client.register(MultiPartFeature.class);
WebTarget target = client.target("https://apisomeurl.com");
MultiPart multiPart = new MultiPart();
multiPart.setMediaType(MediaType.MULTIPART_FORM_DATA_TYPE);
//Image here
FileDataBodyPart fileDataBodyPart = new FileDataBodyPart("image", new File("/some/img/path/img.png"));
multiPart.bodyPart(fileDataBodyPart);
//MediaType.APPLICATION_JSON_TYPE because I'm expecting a JSON response from the server
String str = target.queryParam("param1", "1")
.queryParam("param2", "2")
.queryParam("param3", "3")
.request(MediaType.APPLICATION_JSON_TYPE)
.post(Entity.entity(multiPart, multiPart.getMediaType()), String.class);
The goal is to send an email with inline image. Everything is working well, except the image is not appearing in the email.
My approach is based on this Jersey-example of Mailgun's User Guide.
public static ClientResponse SendInlineImage() {
Client client = Client.create();
client.addFilter(new HTTPBasicAuthFilter("api",
"YOUR_API_KEY"));
WebResource webResource =
client.resource("https://api.mailgun.net/v3/YOUR_DOMAIN_NAME" +
"/messages");
FormDataMultiPart form = new FormDataMultiPart();
form.field("from", "Excited User <YOU#YOUR_DOMAIN_NAME>");
form.field("to", "baz#example.com");
form.field("subject", "Hello");
form.field("text", "Testing some Mailgun awesomness!");
form.field("html", "<html>Inline image here: <img src=\"cid:test.jpg\"></html>");
File jpgFile = new File("files/test.jpg");
form.bodyPart(new FileDataBodyPart("inline",jpgFile,
MediaType.APPLICATION_OCTET_STREAM_TYPE));
return webResource.type(MediaType.MULTIPART_FORM_DATA_TYPE).
post(ClientResponse.class, form);
}
However, I need to use Spring's RestTemplate.
This is what I've got so far:
RestTemplate template = new RestTemplate();
MultiValueMap<String, Object> map = new LinkedMultiValueMap<>();
// ... put all strings in map (from, to, subject, html)
HttpHeaders headers = new HttpHeaders();
// ... put auth credentials on header, and content type multipart/form-data
template.exchange(MAILGUN_API_BASE_URL + "/messages", HttpMethod.POST,
new HttpEntity<>(map, headers), String.class);
The remaining part is to put the *.png file into the map. Not sure how to do that. Have tried reading all its bytes via ServletContextResource#getInputStream, but without success: Image is not appearing in the resulting e-mail.
Am I missing something here?
This turned out to be a case where everything was set up correctly, but only a small detail prevented it from working.
map.add("inline", new ServletContextResource(this.servletContext,
"/resources/images/email-banner.png"));
For Mailgun you need to use the map-key "inline". Also, the ServletContextResource has a method getFilename(), which is used to resolve against the image tag. Thus, the image tag should have the following content id:
<img src="cid:email-banner.png"/>
following is the code I have written to PUT a image to a jersey server.
byte[] img = image(file);// coverts file into byte strea
FormDataMultiPart form = new FormDataMultiPart();
form.field("fileName", file);
FormDataBodyPart fdp = new FormDataBodyPart("fileUpload",
new ByteArrayInputStream(img),
MediaType.APPLICATION_OCTET_STREAM_TYPE);
form.bodyPart(fdp);
ClientResponse rs = wr.type(MediaType.APPLICATION_FORM_URLENCODED).put(
ClientResponse.class, form);
When I am running the code, i am able to send the byte stream to the server, but its returning error that it is not able to find the filename i am providing in form.field, so returning a 400 bad request error?
i am not able to understand what i am missing here?
I was able to fix the my problem. I was not adding multipart. This link helped me
Following is what i did to replace the body-part definition
FormDataBodyPart f = new FormDataBodyPart(FormDataContentDisposition
.name("fileUpload").fileName(file).build(),
new ByteArrayInputStream(img),
MediaType.APPLICATION_OCTET_STREAM_TYPE);
MultiPart multiPart = new FormDataMultiPart().bodyPart(f);
ClientResponse rs = wr.type(MediaType.MULTIPART_FORM_DATA).put(
ClientResponse.class, multiPart);