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);
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;
}
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 !
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 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;
}
}
I am developing an Dynamic Web Application with Eclipse. I have e working MySQL-Database which is connected over a class called 'Data Access Object' (=DAO) that works with JDBC. I want to create entries into this database. The functions are ready. With ready I mean tested and OK. On the same application I implemented Java Jersey's RESTful WebService. It is working well, I can call the service and it returns my desired information. But now to my question:
How can I send a String containing XML? The String has to be parsed in the WebMethod to build and execute the query.
My WebService looks as follows:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import javax.ws.rs.Consumes;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.core.MediaType;
#Path("/input")
public class Input {
//DAO instance to have connection to the database.
//Not used yet.
//private DAO dao = new DAO();
#PUT
#Consumes(MediaType.TEXT_XML)
#Path("/result")
public void putIntoDAO(InputStream xml) {
String line = "";
StringBuilder sb = new StringBuilder();
try {
BufferedReader br = new BufferedReader(new InputStreamReader(xml));
while ((line = br.readLine()) != null) {
sb.append(line);
}
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(sb.toString());
}
}
As you see I tried to print the incoming Stream to the console.
I repeat the most important things:
I know how to parse XML.
I know my DAO works properly.
I know my WebService works as well.
What I would like to know:
How do I send an XML-String to my WebService?
How do I access this String in my PUT-method?
Thank you for your attention and try to help me. I appreciate even every try to.
Kind regards
L.
How do I access this String in my PUT-method?
You can simply code the method to take an argument of type String and Jersey will map this from the incoming XML request, so:
#PUT
#Consumes(MediaType.TEXT_XML)
#Path("/result")
public void putIntoDAO(String xml) {
// ...
}
Should work, with the String containing the full request body.
How do I send an XML-String to my WebService?
This depends on what you're using to send the request to the service, which could be anything which communicates over HTTP. I'll assume you're using Java and sticking with Jersey, so one option is you can use the Jersey Client in the following way:
Client client = Client.create();
WebResource webResource = client.resource("http://localhost:8080/input/result");
String input = "<xml></xml>";
ClientResponse response = webResource
.type("application/xml")
.put(ClientResponse.class, input);
See the Jersey Client documentation for more.
The answer Ross Turner posted is completely correct and working. Here is an option using Apache HttpComponents.
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
public class Runner {
public static void main(String[] args) {
try {
HttpClient httpClient = new DefaultHttpClient();
HttpPut putRequest = new HttpPut("http://localhost:8080/HelloFromJersey/input/result");
StringEntity input = new StringEntity("Hello, this is a message from your put client!");
input.setContentType("text/xml");
putRequest.setEntity(input);
httpClient.execute(putRequest);
httpClient.getConnectionManager().shutdown();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
The server prints:
Hello, this is a message from your put client!