I want a online REST open API (POST Method), which accepts RequestBody as String only.
I have to ping a message to that open API.
restTemplate.postForEntity("myRequestUrl", "my message", String.class);
There are several websites which offer public APIs to test requests, including, but not limited to:
https://httpbin.org / http://httpbin.org/
https://webhook.site
https://test-api.k6.io
https://jsonplaceholder.typicode.com
https://reqres.in
https://fakestoreapi.com
You can also find a list of public APIs at https://github.com/public-apis/public-apis. Those are not necessarily test APIs, but they return real data. Maybe it is useful to somebody.
Related
I am new to Rest web services, and I am trying to figure out what I am doing wrong. When I run on server with the address:
localhost:8080/rest/webresources/error
Then the output message I want (the error message) shows up.
But when I run on the server to show input values using:
localhost:8080/rest/webresources/inputvalues
it doesn't. What am I doing wrong? I feel like my path is wrong, and I tried different combinations of it, but it still gives me a 404 not found error.
#Path("error")
public class RestWeb {
#GET
#Produces(MediaType.TEXT_HTML)
public String getText() {
return "<body> Error. Invalid data. </body>";
}
#POST
#Produces(MediaType.TEXT_HTML)
#Path("/inputvalues")
public String getParamText(#FormParam("travel") String travel,
#FormParam("start") String start,
#FormParam("duration") String end,
#FormParam("party") String people) {
String returnString = processInput(travel, start, end, people);
return "<body> " + returnString + " </body>";
}
Assuming that the REST services were correctly written and deployed, the problem here is the lack of understanding of the way a POST Rest Service is expected to behave as.
From the comment section above it is clear that you are trying to call a POST API directly from a browser.
That can be done fine for a GET type of a service but won't work for a POST type service.
Reason
The REST API uses several HTTP methods to perform various actions on REST resources. Any REST API that uses a GET call can be invoked using a web browser.
A post service however expects a certain set of input parameters (Here in your case, form params "travel", "start", "duration" and "party" are required)
You cannot call POST API's directly by simple typing the path of the Service URL in the browser.
You can use tools like POSTMAN, RESTer and a lot of such software available on the web, with extensive tutorials on how to use these for POST type REST API calls.
I am developing a public REST API service using Netty. I am expecting some users will submit percent-encoded URL, for example with %20 for space.I need to unescape the percent-ecoded URL.
Is there a built in Netty API for this? Or is there any third party Java API for it?
I did search for a solution but could not find one.
Thanks in advance.
Netty has own class for that - io.netty.handler.codec.http.QueryStringDecoder. It is also preferred against java.net.URLDecoder as it is much faster.
Usage example:
//netty http request object
HttpRequest httpRequest = ...;
QueryStringDecoder decoder = new QueryStringDecoder(httpRequest.uri());
decoder.parameters().get("value");
I'm doing a twitter crawler and I have built a search engine on top of it using Lucene. Since many users submit locations that don't exist (e.g. "in my kitchen", "wonderland", "from LA to Paris"...), I think I should check which users to index depending on their location, in orer to make them reachable further with a location-search. I retrieve users by sampling english tweets (using TwitterStream.sample("en")).
My first idea was to download from some web sites all cities in the world and check if there was a match. However, there's a problem with this approach: It's difficult to find a document which contains all cities in the world spelled in all possible languages. The user, indeed, could either submit the name of his city (or country) in english, or in his own language.
You need to use geocoding google maps, yandex maps.
I'm facing the fact that the first link tells google API look for
cities in USA by default. So...if a user says he's in "Paris", google
API will response me NO_REPONSE
Red Light District
I have read the first link with much attention and the second link
with less attention, because the latter seems to be useful just for
javascript application (I'm doing all in java).
No. It is not correct. You can get information by a HTTP request, refer HTTP request parameters.
A small code snippet for yandex maps using apache http client
private void request(String geocode) throws IOException {
HttpResponse response = Request.Post(SEARCH_URL).version(HttpVersion.HTTP_1_1)
.bodyForm(createForm(geocode).build(), Charsets.UTF_8).useExpectContinue()
.connectTimeout(CONNECTION_TIMEOUT_MILS)
.socketTimeout(CONNECTION_TIMEOUT_MILS)
.execute().returnResponse();
assertStatus(response, geocode);
getCoordinatesFromResponse(response, geocode);
}
private Form createForm(String geocode) {
return Form.form().add("format", "json").add("results", "1").add("geocode", geocode);
}
private void assertStatus(HttpResponse response, String requestString) {
StatusLine statusLine = response.getStatusLine();
if (statusLine.getStatusCode() >= ERROR_STATUS_MIN) {
throw new RuntimeException(String.format(
"Error sending request '%s' to the map service, server response: %s",
requestString, response));
}
}
Currently I'm switching to play framework to develop but I'm new to this wonderful framework.
I just want to send a post request to remote server and get response.
If I use Jersey, it would be quite easy, just like this:
WebResource resource = client.resource("http://myfirstUrl");
resource.addFilter(new LoggingFilter());
Form form = new Form();
form.add("grant_type", "authorization_code");
form.add("client_id", "myclientId");
form.add("client_secret", "mysecret");
form.add("code", "mycode");
form.add("redirect_uri", "http://mysecondUrl");
String msg = resource.accept(MediaType.APPLICATION_JSON).post(String.class, form);
and then I can get the msg which is what I want.
But in Play framework, I cannot find any libs to send such post request. I believe this should be a very simple feature and Play should have integrated it. I've tried to search and found most use case are about the Form in view leve. Could anyone give me some help or examples? Thanks in advance!
You can use Play WS API for making asynchronous HTTP Calls within your Play application. First you should add javaWs as a dependency.
libraryDependencies ++= Seq(
javaWs
)
Then making HTTP POST Requests are as simple as;
WS.url("http://myposttarget.com")
.setContentType("application/x-www-form-urlencoded")
.post("key1=value1&key2=value2");
post() and other http methods returns a F.Promise<WSResponse> object which is something inherited from Play Scala to Play Java. Basically it is the underlying mechanism of asynchronous calls. You can process and get the result of your request as follows:
Promise<String> promise = WS.url("http://myposttarget.com")
.setContentType("application/x-www-form-urlencoded")
.post("key1=value1&key2=value2")
.map(
new Function<WSResponse, String>() {
public String apply(WSResponse response) {
String result = response.getBody();
return result;
}
}
);
Finally obtained promise object is a wrapper around a String object in our case. And you can get the wrapped String as:
long timeout = 1000l;// 1 sec might be too many for most cases!
String result = promise.get(timeout);
timeout is the waiting time until this asynchronous request will be considered as failed.
For much more detailed explanation and more advanced use cases checkout the documentation and javadocs.
https://www.playframework.com/documentation/2.3.x/JavaWS
https://www.playframework.com/documentation/2.3.x/api/java/index.html
I have a few questions about a specific REST call I'm making in JAVA. I'm quite the novice, so I've cobbled this together from several sources. The call itself looks like this:
String src = AaRestCall.subTrackingNum(trackingNum);
The Rest call class looks like this:
public class AaRestCall {
public static String subTrackingNum (Sting trackingNum) throws IOException {
URL url = new URL("https://.../rest/" + trackingNum);
String query = "{'TRACKINGNUM': trackingNum}";
//make connection
URLConnection urlc = url.openConnection();
//use post mode
urlc.setDoOutput(true);
urlc.setAllowUserInteraction(false);
//send query
PrintStream ps = new PrintStream(urlc.getOutputStream());
ps.print(query);
ps.close();
//get result
BufferedReader br = new BufferedReader(new InputStreamReader(urlc
.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line=br.readLine())!=null) {
sb.append(line);
}
br.close();
return sb.toString();
}
}
Now, I have a few questions on top of the what is wrong with this in general.
1) If this rest call is returning a JSON object, is that going to get screwed up by going to a String?
2) What's the best way to parse out the JSON that is returning?
3) I'm not really certain how to format the query field. I assume that's supposed to be documented in the REST API?
Thanks in advance.
REST is a pattern applied on top of HTTP. From your questions, it seems to me that you first need to understand how HTTP (and chatty socket protocols in general) works and what the Java API offers for deal with it.
You can use whatever Json library out there to parse the HTTP response body (provided it's a 200 OK, that you need to check for, and also watch out for HTTP redirects!), but it's not how things are usually built.
If the service exposes a real RESTful interface (opposed to a simpler HTTP+JSON) you'll need to use four HTTP verbs, and URLConnection doesn't let you do so. Plus, you'll likely want to add headers for authentication, or maybe cookies (which in fact are just HTTP headers, but are still worth to be considered separately). So my suggestion is building the client-side part of the service with the HttpClient from Apache commons, or maybe some JAX-RS library with client support (for example Apache CXF). In that way you'll have full control of the communication while also getting nicer abstractions to work with, instead of consuming the InputStream provided by your URLConnection and manually serializing/deserializing parameters/responses.
Regarding the bit about how to format the query field, again you first need to grasp the basics of HTTP. Anyway, the definite answer depends on the remote service implementation, but you'll face four options:
The query string in the service URL
A form-encoded body of your HTTP request
A multipart body of your HTTP request (similar to the former, but the different MIME type is enough to give some headache) - this is often used in HTTP+JSON services that also have a website, and the same URL can be used for uploading a form that contains a file input
A service-defined (for example application/json, or application/xml) encoding for your HTTP body (again, it's really the same as the previous two points, but the different MIME encoding means that you'll have to use a different API)
Oh my. There are a couple of areas where you can improve on this code. I'm not even going to point out the errors since I'd like you to replace the HTTP calls with a HTTP client library. I'm also unaware of the spec required by your API so getting you to use the POST or GET methods properly at this level of abstraction will take more work.
1) If this rest call is returning a JSON object, is that going to get
screwed up by going to a String?
No, but marshalling that json into an obect is your job. A library like google gson can help.
2) What's the best way to parse out the JSON that is returning?
I like to use gson like I mentioned above, but you can use another marshal/unmarhal library.
3) I'm not really certain how to format the query field. I assume
that's supposed to be documented in the REST API?
Yes. Take a look at the documentation and come up with java objects that mirror the json structure. You can then parse them with the following code.
gson.fromJson(json, MyStructure.class);
Http client
Please take a look at writing your HTTP client using a library like apache HTTP client which will make your job much easier.
Testing
Since you seem to be new to this, I'd also suggest you take a look at a tool like Postman which can help you test your API calls if you suspect that the code you've written is faulty.
I think that you should use a REST client library instead of writing your own, unless it is for educational purposes - then by all means go nuts!
The REST service will respond to your call with a HTTP response, the payload may and may not be formatted as a JSON string. If it is, I suggest that you use a JSON parsing library to convert that String into a Java representation.
And yes, you will have to resort to the particular REST API:s documentation for details.
P.S. The java URL class is broken, use URI instead.