I'm very new to web-service dev and I'm trying to make a POST request to an API using Jersey. The issue is I think I'm mixing documentation and example I'm finding online between client & server. I'm pretty sure that it's simple but I can't figure out why my code is failing.
Here is my main Class :
import deliveryPayload.Payload;
import jakarta.ws.rs.*;
import jakarta.ws.rs.client.*;
import jakarta.ws.rs.core.HttpHeaders;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import jakarta.ws.rs.core.UriBuilder;
import org.apache.commons.lang3.StringUtils;
import responsePayload.ResponsePayload;
import java.net.URI;
import java.util.*;
#Path("/hook")
public class Hook {
private static final String apiToken = "myToken";
private static final String domain = "url";
private static final String apiUrl = "https://" + domain + "/api/v1/";
#POST
#Consumes(MediaType.APPLICATION_JSON)
public Response eventHook(String body, #HeaderParam("Pass") String password) {
ObjectMapper objectMapper = new ObjectMapper();
Payload payload = new Payload();
try {
payload = objectMapper.readValue(body, Payload.class);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
EventsItem event = payload.getData().getEvents().get(0);
Actor actor = event.getActor();
Response response = ClientBuilder.newClient()
.target(getBaseURI())
.path("apps/" + "someID" + "/users")
.request(MediaType.APPLICATION_JSON)
.header(HttpHeaders.AUTHORIZATION, apiToken)
.post(Entity.entity(actor, MediaType.APPLICATION_JSON));
return response;
}
}
I'm getting this error Parse Error: The response headers can't include "Content-Length" with chunked encoding when using Postman.
Thanks for any help !
Related
I got an exception with validating "status": "OK" in the response body of the DeletePlace request. Request is successful with 200 status code but there is no response body in the log file. Console error is pointing to the Utils line#47. Below is the code & screenshot of the error console pointing error to:
enter image description here
package resources;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.util.Properties;
import io.restassured.RestAssured;
import io.restassured.builder.RequestSpecBuilder;
import io.restassured.filter.log.RequestLoggingFilter;
import io.restassured.filter.log.ResponseLoggingFilter;
import io.restassured.http.ContentType;
import io.restassured.path.json.JsonPath;
import io.restassured.response.Response;
import io.restassured.specification.RequestSpecification;
public class Utils {
public static RequestSpecification req;
public RequestSpecification requestSpecification() throws IOException
{
if (req==null)
{
PrintStream log = new PrintStream(new FileOutputStream("logging.txt"));
req = new RequestSpecBuilder().setBaseUri(getGlobalValue("baseUrl")).addQueryParam("key", "qaclick123")
.addFilter(RequestLoggingFilter.logRequestTo(log))
.addFilter(ResponseLoggingFilter.logResponseTo(log))
.setContentType(ContentType.JSON).build();
return req;
}
return req;
}
public static String getGlobalValue(String key) throws IOException
{
Properties prop = new Properties();
FileInputStream fis = new FileInputStream("E:\\Eclipse-Workspace\\RestAssuredAPIFramework\\src\\test\\java\\resources\\global.properties");
prop.load(fis);
return prop.getProperty(key);
}
public String getJsonPath(Response response, String key)
{
String resp = response.asString();
JsonPath js = new JsonPath(resp);
return js.get(key).toString(); //Error line
}
}
Please help me out and let me know if any other information is required.
I've tried creating getJsonPath method again and all possible fixes I got from various articles but not able to resolved this. I'm expecting the test to execute without any error.
i recommend you to use org.springframework.core.io.Resource to get your properties, like this :
#Value(value = "classpath:your_file.json")
private Resource resource;
after you got your file, try to mapping with :
public static Map<String, Object> jsonToMap(String json) {
try {
final ObjectMapper mapper = new ObjectMapper();
return mapper.readValue(json, new TypeReference<>(){});
}catch (Exception e) {
e.printStackTrace();
}
return null;
}
Having next code, which use RestEasy to get to a Twilio CALL info:
import java.util.Base64;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.Response;
import org.jboss.resteasy.client.jaxrs.ResteasyClient;
import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget;
import com.twilio.rest.api.v2010.account.Call;
public class RestGetCallInfo1 {
public static void main(String[] args) {
try {
ResteasyClient client = new ResteasyClientBuilder().build();
ResteasyWebTarget = client.target("https://api.twilio.com/2010-04-01/Accounts/AC99999999/Calls/CA77777777777.json");
String credentials = "AC99999999:888888888";
String base64encoded = Base64.getEncoder().encodeToString(credentials.getBytes());
Response response = target.request().header(HttpHeaders.AUTHORIZATION, "Basic " + base64encoded).get();
int status = response.getStatus();
if (status == 200) { //OK
Call call = response.readEntity(Call.class); //<------------- This fails!
System.out.println(call);
}
} catch (Exception e) {
e.printStackTrace();
System.exit(-1);
}
}
}
I want to ask you:
What 'Rest' libraries/tools does twilio-7.47.2-jar-with-dependencies.jar use inside (in order to use that instead of RestEasy)?
How can I get the JSON call object properly? with the actual code I get:
javax.ws.rs.ProcessingException: Unable to find a MessageBodyReader of content-type application/json and type class com.twilio.rest.api.v2010.account.Call
EDIT: I am able to get the Call info in JSon format with:
String call = response.readEntity(String.class);
I have worked on small xml body request less than 20 lines and I created key value pairs for it in java.
But I have to use acord xml as payload request to get a response which is more than 250 lines. I tried using form-data to provide as .xml file which is not working.
contentType is xml format and response is received in xml format.
Can somebody please guide me in the right direction, on how to achieve this if coded in a framework?
#Test
public void xmlPostRequest_Test() {
RestAssured.baseURI = "http://localhost:8006";
String requestBody = "<client>\r\n" +
" <clientNo>100</clientNo>\r\n" +
" <name>Tom Cruise</name>\r\n" +
" <ssn>124-542-5555</ssn>\r\n" +
"</client>";
Response response = null;
response = given().
contentType(ContentType.XML)
.accept(ContentType.XML)
.body(requestBody)
.when()
.post("/addClient");
System.out.println("Post Response :" + response.asString());
System.out.println("Status Code :" + response.getStatusCode());
System.out.println("Does Reponse contains '100 Tom Cruise 124-542-5555'? :" + response.asString().contains("100 Tom Cruise 124-542-5555"));
}
You should use a file to pass the xml payload .
Please see the below code and provide a feedback . It's been tested and working .
import static io.restassured.RestAssured.given;
import static io.restassured.RestAssured.when;
import static org.hamcrest.Matchers.is;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import org.json.JSONObject;
import org.testng.Assert;
import org.testng.annotations.Test;
import io.restassured.RestAssured;
import io.restassured.filter.session.SessionFilter;
import io.restassured.http.ContentType;
import io.restassured.path.json.JsonPath;
import io.restassured.path.xml.XmlPath;
import io.restassured.response.Response;
public class XmlExample {
//#Test
public void postComplexXML() throws IOException {
String FilePath="path\\to\\xml.xml";
String XMLBodyToPost=generateStringFromResource(FilePath);
RestAssured.baseURI="http://services.groupkt.com/state/get/IND/UP";
Response res= given().queryParam("key", "value").body(XMLBodyToPost).when().post().then().statusCode(201).and().
contentType(ContentType.XML).extract().response();
//Pass the RrstAssured Response to convert to XML
XmlPath x=rawToXML(res);
//Get country value from response
String country=x.get("RestResponse.result.country");
int size=x.get("result()");
}
public static Response validateXmlResponse() throws IOException {
// Navigate to xml file path attached in project
String FilePath = "c\downloads\filepath;
String XMLBodyToPost = new String(Files.readAllBytes(Paths.get(FilePath)));
// Call the baseUrl to test the request
RestAssured.baseURI = TestURL;
// Getting a reponse for submitted POST request
Response res = given().auth().basic(userName, password).body(XMLBodyToPost).
when().post()
.then()
.statusCode(200).and().contentType(ContentType.HTML).extract().response();
String response = res.asString();
// System.out.println("Returning response as string format:" + " " + response);
return res;
}
I need some help with writing a controller to consume a JSON response from a payment system (Realex).
So far, I have the following from the Realex documentation but can't figure out how to write the controller - i'm new to Spring Boot/Spring MVC.
RealexHpp realexHpp = new RealexHpp("Shared Secret");
HppResponse hppResponse = realexHpp.responseFromJson(responseJson);
// responseJson will be the Java variable containing the JSON response string
String result = hppResponse.getResult();
String message = hppResponse.getMessage();
String authCode = hppResponse.getAuthCode();
So far, i have written:
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.realexpayments.hpp.sdk.RealexHpp;
import com.realexpayments.hpp.sdk.domain.HppResponse;
#Controller
public class PaymentController {
#RequestMapping(value = "/enrolment/confirmation", method = RequestMethod.GET, consumes = "text/plain")
public String process(#RequestBody String responseJson, Model model) throws Exception {
RealexHpp realexHpp = new RealexHpp("secret");
HppResponse hppResponse = realexHpp.responseFromJson(responseJson);
// responseJson will be the Java variable containing the JSON response string
String result = hppResponse.getResult();
String message = hppResponse.getMessage();
String authCode = hppResponse.getAuthCode();
System.out.println("Result: "+result);
System.out.println("Message: "+message);
System.out.println("AuthCode: "+authCode);
model.addAttribute("result", result);
model.addAttribute("message", message);
model.addAttribute("authcode", authCode);
return "enrolment/confirmation";
}
}
Looks like Spring MVC isn't the right tool here.
See: https://github.com/realexpayments/rxp-hpp-java
It's expecting you to use their SDK to generate the repsonseJson:
HppRequest hppRequest = new HppRequest()
.addAmount(100)
.addCurrency("EUR")
.addMerchantId("merchantId");
RealexHpp realexHpp = new RealexHpp("mySecret");
String requestJson = realexHpp.requestToJson(hppRequest);
You might want to be using Spring MVC to capture the parameters for the request.
I am working on restful api of spring and i am send parameters from my browser to my server(localhost). My server will call the link in world wide web and get the result. Here I am getting the exception.
Following is the original link i have to get the
https://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi?db=pubmed&term=science%5bjournal%5d+AND+breast+cancer+AND+2008%5bpdat%5d
THIS IS MY link i call in browser
http://localhost:8080/search?db=pubmed&term=science[journal]+AND+breast+cancer+AND+2008[pdat]
Please help me out.
package com.ncbi.team.utils;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;
import org.springframework.stereotype.Service;
enter code here
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
#Service
public class SearchReq {
public String browseURL(List <String> param )
throwsUnsupportedEncodingExce
ption{
StringBuffer sb = new StringBuffer();
String masterURL = "https://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi";
System.out.println(param);
sb.append(masterURL);
for(int i=0;i<param.size();i++)
{
if(i==0){
sb.append("?");
sb.append(param.get(0));
}
else{
sb.append("&"+param.get(i));
}
}
System.out.println("URL Is :"+sb.toString());
Client c = Client.create();
String url=URLEncoder.encode(sb.toString(),"UTF-8");
// WebResource resource = c.resource(URLEncoder.encode(sb.toString(),"UTF-8"));
WebResource resource = c.resource(url);
//#SuppressWarnings("deprecation")
//WebResource resource = c.resource(sb.toString());
ClientResponse resp = resource.accept("text/html").get(ClientResponse.class);
String xml= null;
if(resp.getStatus() == 200){
xml = resp.getEntity(String.class);
}
return xml;
}
}