There are some other longer solutions I found, but I was wondering if the following works as well:
I have HttpExchange message, that is a POST request that is passed in, and write String jsonPayload = new String(message.getRequestBody().readAllBytes());. Would this turn the request body's json to a string?
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 would like to send this JSON message below, with the HTTP DELETE method.
For this project is necessary to use OAuth2. So I use the dependency google-oauth. Foreach HTTP request I use the dependency google client.
{
"propertie" : true/false,
"members" : [
"String value is shown here"
]
}
In my project I used this code below, but I cannot send the JSON message with the HTTP DELETE method.
Credential credential = new Credential(BearerToken.authorizationHeaderAccessMethod()).setAccessToken(accessToken);
JsonArray members = new JsonArray();
JsonPrimitive element = new JsonPrimitive("String value is shown here");
members.add(element);
JsonObject closeGroupchat = new JsonObject();
closeGroupchat.addProperty("propertie", false);
closeGroupchat.add("members", members);
Gson gson = new Gson();
HttpContent hc = new ByteArrayContent("application/json", gson.toJson(closeGroupchat).getBytes());
HttpRequestFactory requestFactory = httpTransport.createRequestFactory(credential);
HttpRequest httpreq = requestFactory.buildRequest(HttpMethods.DELETE, genericUrl, hc);
return httpreq.execute();
Next error occurs:
java.lang.IllegalArgumentException: DELETE with non-zero content length is not supported
Can someone help me with this problem?
Your problem is that your HTTP DELETE request contains a body, which it shouldn't. When you delete a resource, you need to supply the URL to delete. Any body in the HTTP request would be meaningless, because the intention is to instruct the server to delete a resource at a particular URL. The same thing can often happen for GET requests - a body is meaningless because you're trying to retrieve a body.
For details on HTTP DELETE request bodies, see this SO question on the subject. Note that while request bodies may technically be permitted by the HTTP spec, based on your error message, your client library doesn't allow it.
To fix the problem, try passing a null value for hc, or a value that just wraps an empty JSON string (by which I mean using "", not "{}").
I'm at a loss for how to process results from a post in play framework. The following code works to process a GET response:
WSRequestHolder request = WS.url(myURL);
return async(
request.get().map(
new Function<WS.Response, Result>() {
public Result apply(WS.Response response) {
String json = response.getBody();
System.out.println("Json response: " + json);
//Do stuff
return ok(json);
}
}
)
);
I thought I'd just be able to replace .get() with post(myvalue). However, this does not work. What is the proper way to process a POST response in Play Framework?
WSRequestHolder.post(...) accepts 4 different types as a parameter: java.io.File, java.io.InputStream, JsonNode and String. You can replace .get() with .post(myvalue), depending on what myvalue is and what Content-Type myURL is expecting.
POSTing with those types will set the Content-Type header appropriate to the type. Passing a JsonNode will automatically set the Content-Type to application/json, for example. However, when passing a String you will likely have to set the Content-Type yourself, as Play isn't going to know whether that String is supposed to be JSON or a form.
From the Play Documentation:
If you're sending a form:
request.setContentType("application/x-www-form-urlencoded").post("key1=value1&key2=value2") ...
Or posting JSON as a String:
request.setContentType("application/json").post(jsonString) ...
If you're having other compile errors, please post them.