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;
}
}
Related
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 !
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;
}
Edit:
I tried to implement the suggestions of #Durgpal Singh and #Nikhil. I changed the code so it looks like this.
Client:
Client client = ClientBuilder.newClient();
WebTarget target = client
.target("http://localhost:8087/api/ls3algorithm/" + petrinets + "/" + Integer.toString(k) + "/" + Float.toString(theta));
Invocation.Builder invocationBuilder = target.request(MediaType.APPLICATION_JSON);
Response response = invocationBuilder.get();
Map<String, List<Map>> result_ = response.readEntity(new GenericType<Map<String, List<Map>>>() { });
result = (ArrayList<Map>) result_.get("data");
Server:
ArrayList<Map> result;
result = new Ls3Algorithm().execute(new File("petrinetze").getAbsolutePath(), k, theta);
Map<String, List<Map>> map = new HashMap<>();
map.put("data", result);
return Response.ok(map).build();
Unfortunately this leads to Exception in thread "main" org.glassfish.jersey.message.internal.MessageBodyProviderNotFoundException: MessageBodyReader not found for media type=application/json, type=interface java.util.Map, genericType=java.util.Map<java.lang.String, java.util.List<java.util.Map>>.
Where do I go wrong?
-------------------------------
I'm pretty new to RESTful web services and currently writing a microservice which provides a calculating algorithm. I'm testing the service as posted below.
Workflow:
Client saves some data in a MongoDB database and sends the names of the relevant files via #PathParam as part of the GET request. The server then retrieves the files from the MongoDB, processes its algorithm and sends back the result as List<Map> packed in a Response object.
Goal:
Transfer the result (List<Map>) as JSON and print it out on the client console.
Client:
package ls3test;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Map;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Invocation;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.GenericType;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectWriter;
import com.mongodb.DB;
import com.mongodb.MongoClient;
import com.mongodb.gridfs.GridFS;
import com.mongodb.gridfs.GridFSInputFile;
public class Ls3TransmissionTest {
final static String petrinets = "eins, zwei, drei, vier";
final static int k = 3;
final static float theta = 0.9f;
public static void main(String[] args) throws IOException {
[... save all the relevant files in the MongoDB ...]
ArrayList<Map> result = new ArrayList<Map>();
Client client = ClientBuilder.newClient();
WebTarget target = client
.target("http://localhost:8087/api/ls3algorithm/" + petrinets + "/" + Integer.toString(k) + "/" + Float.toString(theta));
Invocation.Builder invocationBuilder = target.request(MediaType.APPLICATION_JSON);
Response response = invocationBuilder.get();
result = response.readEntity(new GenericType<ArrayList<Map>>() {
});
ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
String json = ow.writeValueAsString(result);
}
}
Server:
package service;
import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.mongodb.DB;
import com.mongodb.MongoClient;
import com.mongodb.gridfs.GridFS;
import com.mongodb.gridfs.GridFSDBFile;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.GenericEntity;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.util.List;
import java.util.Map;
#SuppressWarnings("deprecation")
#Path("/ls3algorithm")
public class Resource {
// SLF4J is provided with Dropwizard
Logger log = LoggerFactory.getLogger(Resource.class);
#SuppressWarnings("rawtypes")
#GET
#Path("/{petrinets}/{k}/{theta}")
#Produces(MediaType.APPLICATION_JSON)
public Response ls3execute(#PathParam("petrinets") String petrinetNames, #PathParam("k") int k,
#PathParam("theta") float theta) {
[... get all the relevant files from the MongoDB ...]
List<Map> result;
Ls3Algorithm ls3Algorithm = new Ls3Algorithm();
result = ls3Algorithm.execute(new File("petrinetze").getAbsolutePath(), k, theta);
GenericEntity<List<Map>> entity = new GenericEntity<List<Map>>(result) {};
Response response = Response.ok(entity).build();
return response;
}
}
This is not working, the exception I get is posted below:
Exception in thread "main" org.glassfish.jersey.message.internal.MessageBodyProviderNotFoundException: MessageBodyReader not found for media type=application/json, type=class java.util.ArrayList, genericType=java.util.ArrayList<java.util.Map>.
at org.glassfish.jersey.message.internal.ReaderInterceptorExecutor$TerminalReaderInterceptor.aroundReadFrom(ReaderInterceptorExecutor.java:231)
at org.glassfish.jersey.message.internal.ReaderInterceptorExecutor.proceed(ReaderInterceptorExecutor.java:155)
at org.glassfish.jersey.message.internal.MessageBodyFactory.readFrom(MessageBodyFactory.java:1085)
at org.glassfish.jersey.message.internal.InboundMessageContext.readEntity(InboundMessageContext.java:874)
at org.glassfish.jersey.message.internal.InboundMessageContext.readEntity(InboundMessageContext.java:834)
at org.glassfish.jersey.client.ClientResponse.readEntity(ClientResponse.java:368)
at org.glassfish.jersey.client.InboundJaxrsResponse$2.call(InboundJaxrsResponse.java:126)
at org.glassfish.jersey.internal.Errors.process(Errors.java:315)
at org.glassfish.jersey.internal.Errors.process(Errors.java:297)
at org.glassfish.jersey.internal.Errors.process(Errors.java:228)
at org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:419)
at org.glassfish.jersey.client.InboundJaxrsResponse.runInScopeIfPossible(InboundJaxrsResponse.java:267)
at org.glassfish.jersey.client.InboundJaxrsResponse.readEntity(InboundJaxrsResponse.java:123)
at ls3test.Ls3TransmissionTest.main(Ls3TransmissionTest.java:89)
Ls3TransmissionTest.java:89 is ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
I spent plenty of time now doing research on this problem, but I cannot find an example that really fits it. What do I miss? Any help or hint is highly appreciated!
You can send a map. Like this
Map<String, Object> map = new HashMap<>();
map.put("data", entity);
Response.ok(map).build();
return Response;
Cannot see why do you need to wrap the List with GenericEntity. Something as simple as below will work:-
#SuppressWarnings("rawtypes")
#GET
#Path("/{petrinets}/{k}/{theta}")
#Produces(MediaType.APPLICATION_JSON)
public Response ls3execute(#PathParam("petrinets") String petrinetNames, #PathParam("k") int k,
#PathParam("theta") float theta) {
//[... get all the relevant files from the MongoDB ...]
List<Map> result;
Ls3Algorithm ls3Algorithm = new Ls3Algorithm();
result = ls3Algorithm.execute(new File("petrinetze").getAbsolutePath(), k, theta);
Response response = Response.ok(result).build();
return response;
}
And in the client side,
String result = response.readEntity(String.class);
return result;
Hi I have implemanted one basic example of RESTful web services ,I am trying to implement Oauth client and Server (Provider) in my src folder of eclipse.
This is my OauthClient.java
import javax.annotation.security.RolesAllowed;
import javax.ws.rs.GET;
import javax.ws.rs.Produces;
import javax.ws.rs.Path;
import com.sun.jersey.api.client.*;
import com.sun.jersey.oauth.client.OAuthClientFilter;
import com.sun.jersey.oauth.signature.OAuthParameters;
import com.sun.jersey.oauth.signature.OAuthSecrets;
import javax.ws.rs.core.*;
#Path("/OauthClient")
#RolesAllowed({"admin"})
public class OauthClient
{
#GET
#Path("/oauth_client")
#Produces(MediaType.TEXT_PLAIN)
public String oauthClient()
{
// establish the parameters that will be used to sign the request
OAuthParameters params = new OAuthParameters().consumerKey("hoge").signatureMethod("HMAC-SHA1").timestamp().nonce().version("1.1").token("sho1get");
// establish the secrets that will be used to sign the request
OAuthSecrets secrets = new OAuthSecrets().consumerSecret("testtest").tokenSecret("testtest");
Client client = Client.create();
// OAuth test server resource
WebResource resource = client.resource("http://localhost:8080/RestfulWS/rest/OauthServer/oauth_provider");
// if parameters and secrets remain static, filter can be added to each web resource
OAuthClientFilter filter = new OAuthClientFilter(client.getProviders(), params, secrets);
// filter added at the web resource level
resource.addFilter(filter);
System.out.println("==== Client =====");
// make the request (signing it in the process)
return resource.get(String.class);
}
}
and OauthServer.java is
import javax.annotation.security.RolesAllowed;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
//import com.sun.jersey.api.client.UniformInterfaceException;
import com.sun.jersey.api.core.HttpContext;
import com.sun.jersey.oauth.server.OAuthServerRequest;
import com.sun.jersey.oauth.signature.OAuthParameters;
import com.sun.jersey.oauth.signature.OAuthSecrets;
import com.sun.jersey.oauth.signature.OAuthSignature;
import com.sun.jersey.oauth.signature.OAuthSignatureException;
#Path("/OauthServer")
#RolesAllowed({"admin"})
public class OauthServer {
#GET
#Path("/oauth_provider")
#Produces(MediaType.TEXT_PLAIN)
public String oauthProvider(#Context HttpContext context)
{
// wrap an existing request with server request
OAuthServerRequest request = new OAuthServerRequest(context.getRequest());
// baseline OAuth parameters for access to resource
OAuthParameters params = new OAuthParameters().readRequest(request);
// OAuth secrets to access resource
OAuthSecrets secrets = new OAuthSecrets().consumerSecret("hoge").tokenSecret("testtest");
// String timestamp = params.getTimestamp();
try {
/* The error occurs here. */
if (OAuthSignature.verify(request, params, secrets)) {
return "OK";
}
} catch (OAuthSignatureException e) {
// log.warning(e.getMessage());
// } catch (UniformInterfaceException e) {
//// log.warning(e.getMessage());
// } catch (Exception e) {
// log.warning(e.getMessage());
}
return "ERROR";
}
}
how to run this to achive Oauth authentication ,do we have to write some JSP? please suggest something.