How to make a REST Webservice call in JAVA? - java

Currently I have a web service running in a tomcat (http://localhost:8080/myApp/getUsers). My web service will accept a json string and then process accordingly. My webservice code is as follows:
#Path("/getUsers")
public class UsersWS
{
#POST
public Response post(String theRequestJSON)
{
try
{
JSONObject aJsonObj = new JSONObject(theRequestJSON);
String userID = aJsonObj.getString("userID");
System.out.println(userID);
}
}
}
So, my Web service is processing a json string. So now, I need to call the above web service from another JAVA class (with a jsonObject having the userID in request parameter).
How to do it? Shortly, I need to make a web service call from a JAVA class with a JSON object as a request parameter. How to send a json as a request parameter in a request call.

Take a look at Jersey: http://jersey.java.net
Here's a good write up on how to use the client:
http://blogs.oracle.com/enterprisetechtips/entry/consuming_restful_web_services_with

Use native URLConnection or Apache HttpClient to send a HTTP request to the server.And the parameters must passed in key=value&key2=value2... format. So you may need to reconstruct the JSON object in that format or using another special parameter name like data=jsonstring then parse the json string using some library.

#George has basically already answered your question, but in terms of JSON processing you may want to also look at Jackson http://jackson.codehaus.org/
This allows you to quickly convert Java objects to JSON equivalents.

Related

What is the easiest way to integrate aws gateway api with Lambda java function and pass json data between them?

My goal is to build a set of REST apis using aws api gateway, back with java Lambda functions and DynamoDB. The payload of the requests and responses is json. I want to avoid tedious field level mapping code between json and java and between java and dynamodb so am trying to use gson to map json to java objects the enhance dynamodb client so I can use java pojos as inputs and outputs of dynamodb queries. This all works fine when testing the functions stand alone.
The issue I am having is passing json between the Gateway and Lambda when trying to integrate gateway apis to the functions. I've tried the two interfaces of Lambda functions, RequestHandler and RequestStreamHandler. I can each of these to do half of what I need, but with RequestHander I have an get runtime errors when returning the response body as json, with RequestStreamHandler I can successfully set the response body as json, but I have problems receiving the request body as json.
It seems that something in the aws gateway framework is converting the body json into an escaped string and then another part of the framework is trying to convert the escaped string into json and failing.
What I am trying to do would seem the most basic REST api use case for aws gateway and Lambda, but I can't find any code examples in aws documentation beyond the trivial "hello world" type. Aws documentation seems pretty thin too, so has anyone out there been successfully in building REST apis with json payloads using aws gateway and Lambda who could share the secret of success?
Here's a bit of background as to what I've tried:
API Gateway:
I've created gateway apis using Lambda proxy integration to my Lambda functions. I've not specified any models to validate the input. I've just taken the default settings. I am passing a json object as the body of my HTTP requests to test the apis.
Lambda Functions
Coded in java using V2 of the SDK.
RequestHandler function - I have created a class the implements the RequestHandler interface specifying the input parameter as a HashMap and output as String. I have successfully got the body of the HTTP request from the hashmap and used Gson to convert the body to my Java pojo. All good.
However I fail trying to include json as the body of the response. I've used both Gson and org.json to construct my http response and include json as the body. I can unit test the function successfully, but when integrated with my gateway api I get an error in the gateway (not that the response has been escaped):
Tue Jan 12 11:12:23 UTC 2021 : Endpoint response body before transformations: "{"body":{"message":"hello world"},"isBase64encoded":false,"statusCode":200}"
Tue Jan 12 11:06:59 UTC 2021 : Execution failed due to configuration error: Malformed Lambda proxy response
RequestStreamHandler
The signature of the handleRequest method is:
public void handleRequest(InputStream input, OutputStream output, Context context)
In this case, I can successfully create a json response using gson and write it to the output stream and the api gateway is fine with it.
However I have a problem with the input. I have tried to use gson to parse the input stream and extract the body. This is fine, but the body is not json, it is an escaped json string, for example:
"{\r\n "id": "10",\r\n "title": "Ski trips",\r\n "owner": "captain",\r\n "locations": \r\n [\r\n {"latitude": 55, "longitude":-2 }\r\n ]\r\n}"
I can't use Gson to parse this nor use Gson to convert it to a pojo. If I try then I get runtime exceptions. To get round this I have used org.apache.commons.text.StringEscapeUtils to remove the escape characters and then removed the leading and trailing quotes round the string. I can then use Gson to convert the resultant string to my pojo class. This is tedious in the extreme.
I've tried changing the classes used for the inputs and outputs of the handleRequest methods, for example to return a JsonObject to see if that changed what I receive but to no avail. If the body contains just a string rather than json, then there is no problem. So just returning "hello world" as the body is fine as per the examples I've found.
I must be missing something, possible in the definition of the gateway api or in the types of the input and output parameters of the Lambda functions but without documentation it really is just wandering around in the dark. Hey all I want to do is to take a json object from the body of a rest request and write it as a json document to a nosql database, getting tripped up by conversion and mapping is really frustrating.
Thanks to anyone who can help me.
Lets say this is our Hander class with ApiGatewayRequest and ApiGatewayProxyResponse are request and response class names.
public class MyHandler implements RequestHandler<ApiGatewayRequest, ApiGatewayProxyResponse> {
#Override
public ApiGatewayProxyResponse handleRequest(ApiGatewayRequest request, Context context) {
}
}
Request Class
public class ApiGatewayRequest {
private String body;
private Map<String, String> headers;
private Map<String, String> queryStringParameters;
private Map<String, String> pathParameters;
private boolean isBase64Encoded;
}
Response Class
public class ApiGatewayProxyResponse {
private int statusCode;
private Map<String, String> headers;
private String body;
}
Json string should be sent in body with com.fasterxml.jackson.databind.ObjectMapper something like
String body = new ObjectMapper().writeValueAsString(ouputObject)
necessary headers ex: Access-Control-Allow-Credentials, Access-Control-Allow-Origin or Content-Type
I have solved my own problem. In aws gateway I had chosen my api to be of type Rest, which seemed the obvious choice for creating Rest services accessed over HTTP. I created a new api of type Http to integrate with the same Lambda function and to cut a long story short that solved the problem. The body of my post request as passed to the Lambda function is not escaped and can be process as json, and likewise the body in my response is not escaped or rejected before being returned to an http client. However I found this out through trial and error rather than by following clear documentation or working examples. My next step is to implement examples of get, post, put and delete HTTP methods to understand how parameters are passed in the case of path variables and query strings, as well as completing the integration with dynamodb. I'll post my working code once done.

How can send multiple params on a get request

First of all, give thanks for reading my question and try to help me and apologize for my English.
I'm new with Spring and I have this message:
A servlet request to the URI
http://localhost:8080/backend/v1/streetviewer/search-street?url=backend2?busqueda=name%20street&idioma=es-es%26cantidad=10
contains form parameters in the request body but the request body has been consumed by the servlet or a servlet filter accessing the request parameters. Only resource methods using #FormParam will work as expected. Resource methods consuming the request body by other means will not work as expected.
My backend send a request to backend2 with one parameter (url), but that url contains 3 parameters. I understand that is reason why say that.
But I was reading that #FormParam is used for POST requests and I'm using #QueryParam.
#GET
#Path(ApiPath.PATH_BACKEND2)
public String getDataFromProdServer(#QueryParam(ApiParam.PARAM_URL) final String externalUrl ) {
return mapService.ServerRequest(externalUrl);
}
How can solve it??
To be said you are actually using JAX-RS Implementation, from backend2 I asume it is a separate service so I suggest you to use Spring Implementations for consuming the API. #RequestMapping/#GetMapping and so..
Coming to the question (With Spring Implementation)
#GetMapping(ApiPath.PATH_BACKEND2)
public String getDataFromProdServer(#RequestParam(ApiParam.PARAM_UR) final String externalUrl) {
return mapService.serverRequest(externalUrl);
}

Android Json Post to ServiceStack web service

Good morning all,
I am following this json post to server tutorial, , which is so far working very well, until I hit an issue saving the post to a c# service stack web service.
When I debug the json = jsonObject.toString(); it returns the following valid json.
{"name":"Test Name","country":"Test Country","twitter":"Test Twitter"}
As a general test, my web service looks like the following.
public object Any(String jsonString)
{
return jsonString;
}
But the response that I get back strips the " out of the string.
{name:Test Name,country:Test Country,twitter:Test Twitter}
With my limited understand of JAVA currently, I am guessing that the tutorial is correct and works fine, but the c# method just will not accept the json string correctly?
Thank you
You should only use Request DTO's as the argument for ServiceStack Services (i.e. never Strings), e.g:
public class MyRequest
{
public string Name { get; set ;}
public string Country { get; set ;}
public string Twitter { get; set ;}
}
public object Any(MyRequest request)
{
return request;
}
Returning a POCO enables ServiceStack to provide automatic Content Negotiation for your Response DTO's.
But returning a raw string in a ServiceStack Service gets written as-is, i.e. ServiceStack doesn't apply any further processing to string responses.
Java Add ServiceStack Reference for Android
If you're looking to invoke ServiceStack Services from Android you should consider Java Add ServiceStack Reference which enables a typed end-to-end API for consuming ServiceStack Services from Java/Android.

Jersey mthod argument without annotations

In RESTful web services written using Jersey, I know I can access path parameters and query string parameters using #PathParam and #QueryParam annotaions. But in a web service written by someone else I saw a method like below.
#POST
#Path("/sms/receive")
#Consumes("application/json")
#Produces("application/json")
public Response smsReceive(String jsonBody) {
//Code here...
}
There is no #PathParam or #QueryParamannotation before the argument jsonBody.
Can anybody explaing what this argument means and how to set value for it when calling this service.
Can I use multiple parameters without annotations?
Thanks.
The service above does not handle query or path parameters at all.
It #Consumes JSON input. That's what the method's parameter jsonBody is referring to.
If someone would want to instruct this service he would add a json payload to the http request which the service (in this case) receives as a simple String. The String then needs to be parsed.
Of course you can combine Path/Query Parameters with JSON Payloads.

Pass an URL as param in RESTful WebServices

I'm defining a RESTful WebService in Java.
It takes as input:
an username (for instance, jdoe);
an URL (for instance: https://blablablabla.io/sample?boh=mah).
By using GET method of the HTTP protocol, it should produce a JSON file.
Which is the best way to pass these params?
In this particular case, is there a best practice to follow in order to properly pass an URL as param?
You must first encode it, you can use
URLEncoder.encode("url");
If you want to define an http GET method, then the only way to pass parameters to it is through the URI query string (ie. ?x=y&...).
This is because GET calls can not take in a message body.
If you want to pass in more complicated information, you will need to use POST, PUT, or some other method. Though, if you are actually just getting information (semantically), then you shouldn't use anything but GET.
Also you can use Path parameters
This is example
#Path("/users")
public class UserResorce {
#GET
#Path("/{username}")
#Produces(MediaType.APPLICATION_JSON)
public String getUser(#PathParam("username") String username)){
}
}
The url is http://domain_name/your_application_path/users/username

Categories

Resources