I am working on java application for getting attachments from salesforce.
I have to show the salesforce attachments in my java application for particular object like Leads,Contacts etc. For that i am using Rest Api and got response body. But in response body there is url but i want binary data of attachment body.
I get response in body in following format:
{
Body = "/services/data/v23.0/sobjects/Attachment/00P90000004SRFlEAO/Body";
ContentType = "application/video";
Name = "Video.MOV";
attributes = {
type = Attachment;
url = "/services/data/v23.0/sobjects/Attachment/00P90000004SRFlEAO";
};
}
You get the actual attachment by performing a GET request to the Url returned in the Body field.
Related
I am consuming a legacy rest service that receives xml text in the body but is sent as json as shown in the following image
Postman source request
I have done the process to transform the previous request to a request that receives a JSON in normal format
New JSON request
And then I transform it into the format that asks me for the source request, my problem is that I do not know how to send my string request because I get the following error when I try to send it
Request error new http request
I get the same error when I sent in my source request in plain text format
Plain text error legacy http request
however in code I already transformed this text into JSON format but probably incorrectly,in the following sample code the http entity is the xml string object required by the legacy service
#Value("${client.medExpInsuranceQuotation.uri}")
private String clientUri;
#Autowired
#Qualifier("restTemplategetPolicyWs")
private RestTemplate restTemplate;
#Override
public Object callMedicalExpenseInsuranceQuotation(MedicalExpenseInsuranceQuotationRequestClient requestClient) {
Gson gson = new Gson();
Object json = gson.toJson(requestClient.getXml(), String.class);
System.out.println("Object: "+json);
HttpEntity<Object> entity = new HttpEntity<>(json);
log.info(requestClient.getXml());
ResponseEntity<ResponseBean<Object>> responseEntity = restTemplate.exchange(clientUri, HttpMethod.POST, entity, new ParameterizedTypeReference<ResponseBean<Object>>() {
});
return responseEntity.getBody().getPayload();
}
Notes:
The legacy service only receives the body in the format indicated in image 1 (Postman source request)
if I try to send the body in traditional json format with an attribute identifier
attemp send normal json format
I get the following error without information
{
"Message": "An error has occurred."
}
I hope you can help me greetings
That rest service is consuming json format. Note the double quotes at the start and the end of the payload - this makes it json string. Not json object, or json array, but json string. You need to transform the xml payload into json string and send the correct content type header - application/json.
Edit: To get json string first you need the xml as a string(it's already a string, i know that sounds strange, but can't explain it better). Then you call toJson() on that xml. Something similar to this:
String xml = "<xml><tag></tag></xml>";
String jsonString = gson.toJson(xml);
System.out.println(jsonString);
I am trying to build a Rest API automation based on Java, RestAssured, and Cucumber. I ' trying to hit an endpoint via POST. The problem is when I am converting the response as string and when I print the response, it is printing the XML file contents but not the response. I also see the status code as 200. I'm not sure what is going wrong in here. Below is the sample snippet from my codebase.
I am trying to hit a WebService (SOAP WSDL).
// required imports
public class Service_Steps {
Response xmlResponse;
#When("I create a POST request for RCP for endpoint using XML")
public void i_create_a_post_request_for_endpoint_using_xml() {
// xml Request body
String path = "pah_to_xml_file";
File file = new File(path);
xmlResponse = RestAssured.given().when().relaxedHTTPSValidation().accept(ContentType.XML).header(<headers>)
.body(file)
.post(url);
String xmlResponseAsString = xmlResponse.then().extract().body().asString();
}
Not sure why I am seeing this ambiguity. Sometimes it is printing the response, and sometimes it is printing the XML file (request body) contents.
After checking with developers I came to know that the SOAP EndPoint is sending out the responses in two different ways, randomly!
Try this one:
xmlResponse = RestAssured.given().log().all().when().relaxedHTTPSValidation().accept(ContentType.XML).header(<headers>)
.body(file)
.post(url)
.then()
.log().all()
.extract()
.response();
This will print out all the request & response stuff
How to post request JSON Data and attach file to upload
actually there is a form which contains attachment so how to send request to fill form and attach image file
Response response = given().config(config).header(key, value).header(contentType, "multipart/mixed")
.multiPart("attachment[]", upleadFile).body(jsonBody).when().post(apiURL).then().statusCode(200).extract().response();
I have got solution use this.
In first we are passing exact key like attachment[]
and for other objects
{
Response response =
given().header(key, value).
multiPart("attachment[]", new File("E:/Lightshot/Screenshot_2.png")).
multiPart("issueTypeId", json.get("issueTypeId").toString()).
multiPart("relationJson",json.get("relationJson").toString()).
multiPart("url",json.get("url").toString())
.when().post(apiURL).then().statusCode(200).extract().response();
return response;
}
I am trying to download a file from a REST service using JAX-RS.
This is my code which invokes the download by sending a GET request:
private Response invokeDownload(String authToken, String url) {
// Creates the HTTP client object and makes the HTTP request to the specified URL
Client client = ClientBuilder.newClient();
WebTarget target = client.target(url);
// Sets the header and makes a GET request
return target.request().header("X-Tableau-Auth", authToken).get();
}
However I am facing problems converting the Response into an actual File object. So what I did is the following:
public File downloadWorkbook(String authToken, String siteId, String workbookId, String savePath)
throws IOException {
String url = Operation.DOWNLOAD_WORKBOOK.getUrl(siteId, workbookId);
Response response = invokeDownload(authToken, url);
String output = response.readEntity(String.class);
String filename;
// some code to retrieve the filename from the headers
Path path = Files.write(Paths.get(savePath + "/" + filename), output.getBytes());
File file = path.toFile();
return file;
}
The file which is created is not valid, I debugged the code and noticed that output contains a String like that (much larger):
PK ͢�F���� �[ Superstore.twb�ysI�7����ߡ���d�m3��f���
Looks like binary. Obviously there is something wrong with the code.
How do I get the HTTP response body as a string from the Response object?
Edit:
Quote from the REST API reference about the HTTP response:
Response Body
One of the following, depending on the format of the workbook:
The workbook's content in .twb format (Content-Type: application/xml)
The workbook's content in .twbx format (Content-Type: application/octet-stream)
As you noticed yourself, you're dealing with binary data here. So you shouldn't create a String from your response. Better get the input stream and pipe it to your file.
Response response = invokeDownload(authToken, url);
InputStream in = response.readEntity(InputStream.class);
Path path = Paths.get(savePath, filename);
Files.copy(in, path);
1) I assume by this point you're clear on the difference between "binary file" and "text file". And that you can only capture the latter into a "string".
2) Sebastian gave you excellent advice for capturing a binary file (+1, Sebastian!). VERY IMPORTANT: you should always set the MIME type (Content-Type: xxx/yyy)in cases like this. Here is another link that might be useful.
3) Finally, there are cases where you might WANT to treat "binary" data as text. This is how e-mail attachments work with SMTP (a text protocol). In these cases, you want to use Base64 Encoding. For example: JAX-RS | Download PDF from Base64 encoded data
In my java client application, I am accessing a endpoint URL and could able to get response back, but it is in HTML code!.
Method : Post
resource.accept(MediaType.APPLICATION_JSON_TYPE);
WebResource resource = Client.create().resource(
communicatorVO.getTargetURL());
String **response** = resource.queryParams(communicatorVO.getFormData()).type(MediaType.APPLICATION_JSON_TYPE).post(String.class, gson.toJson(communicatorVO.getRequestObject()));
The response object always contains HTML code! How to get the actual data?
If I try using chrome restful client, am getting below response.
{
"access_token" : "YOUR_NEW_ACCESS_TOKEN",
"token_type" : "bearer",
"expires_in" : 10800,
"refresh_token" : "YOUR_REFRESH_TOKEN",
"scope" : "write read offline_access"
}
This issue has been resolved.
I added type & accept in single line and it started returning expected json response. Now I can parse the json into any java object.
Code :
response = resource.type(MediaType.APPLICATION_FORM_URLENCODED_TYPE).accept(MediaType.APPLICATION_JSON_TYPE).post(ClientResponse.class, communicatorVO.getFormData());;