I am completely new to Java web services. I have written following code:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class Main {
public static void main(String[] args) {
try {
URL url = new URL("www.somehost.com/somedata");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/json");
if (conn.getResponseCode() != 200) {
throw new RuntimeException("Failed: HTTP error code: " + conn.getResponseCode());
}
BufferedReader br = new BufferedReader(new InputStreamReader(
conn.getInputStream()
));
String output;
while ((output = br.readLine()) != null) {
System.out.println(output);
}
conn.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
}
My task is to create a web service that returns data in JSON format from "some URL". I want to create a RESTful web service but I do not realize how to modify the code to serve it as a web service. Can anybody explain/show what else I should do?
Here is a Jersey resource example:
#Path("rest/heartbeat")
public class HeartbeatResource {
#GET
#Produces(MediaType.APPLICATION_XML)
public Response heartbeatGet() {
return Response.status(Status.OK).type(MediaType.APPLICATION_XML)
.entity(new Messages("I am alive!")).build();
}
}
Do some research and choose a solid REST framework, if it happens to be Jersey then you can find needed learning documents at: https://jersey.java.net/
I prefer Apace Wink to develop RESTful services.. It gives you capability to tune the API as per you need .
http://wink.apache.org/
Related
I'm using Positionstack API to build my APP with a location function on Android. The API works well when I test it on java in the local environment. However, it keeps returning a syntax error message and an Error 400 code when I send the request on Android Studio through an activity.
The error message
I/System.out: 400
I/System.out: {"error":{"code":"bad_request","message":"Could not decode value from JSON format. Error was: \u0022Syntax error\u0022."}}
The class of sending requests. It works well in the local environment but fails on the emulator. It establishes a HttpUrlConnection and uses the GET method to retrieve the result from API. It returns a 400 status code on the Android Studio emulator.
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class NetTest {
public static String sendRequest(String urlParam, String coordinate){
HttpURLConnection con = null;
BufferedReader buffer = null;
StringBuffer resultBuffer = null;
InputStream is;
try{
// prepare the params and send request
URL url = new URL(urlParam);
con = (HttpURLConnection) url.openConnection();
con.setConnectTimeout(5000);
con.setReadTimeout(5000);
con.setRequestMethod("POST");
con.setRequestProperty("Content-Type","application/json;charset=UTF-8");
con.setDoOutput(true);
con.set
// DataOutputStream wr = new DataOutputStream(con.getOutputStream());
// wr.writeBytes("access_key=xxx");
// wr.writeBytes("query=-33.7,127");
// wr.flush();
// wr.close();
System.out.println("message out");
// receive response
int responseCode = con.getResponseCode();
System.out.println(responseCode);
if (responseCode == 200) {
is = con.getInputStream();
}else {
is = con.getErrorStream();
}
resultBuffer = new StringBuffer();
String line;
buffer = new BufferedReader(new InputStreamReader(is,"UTF-8"));
while ((line = buffer.readLine()) != null){
resultBuffer.append(line);
}
return resultBuffer.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return "";
}
public static void main(String[] args) {
String coordinate = "-33.7,127";
String url = "http://api.positionstack.com/v1/reverse";
System.out.println(sendRequest(url,coordinate));
}
}
The manifest
<application
android:usesCleartextTraffic="true">
...
</application>
<uses-permission android:name="android.permission.INTERNET" />
Thanks a lot!
The problem may be the encoding method of Android, but I don't know how to change it, or even see it.
Use this codeblock -> first create jsonObject and add your key values and then set in output Stream. you can use this link for reference -> https://www.baeldung.com/httpurlconnection-post
JSONObject jsonObject = new JSONObject();
jsonObject.put("access_key", "Enter your access key here");
jsonObject.put("query", "Enter your query string here");
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
String jsonString = jsonObject.toString();
byte[] input = jsonString.getBytes(StandardCharsets.UTF_8);
wr.write(input, 0, input.length);
wr.flush();
wr.close();
Also check the logger for what is sent in request body, use okhttp as search string in logger
Thanks to #abhishekrajak. I think his answer can solve most questions in this case.
In my case, however, I received an Error 403 status code from the API that said that my subscription couldn't use this service. I think the problem is that using OutputStream of HttpUrlConnection will automatically transfer your request method from "GET" to "POST", and my subscription is only able to receive the "GET" service.
Anyway, no doubt that #abhishekrajak 's answer can successfully pass the parameter in the correct encoding.
I solved this problem by using an alternative API. The original API may not be a good choice in the first place.
I want to call GET and POST API in java without using any framework. I need to use basic authentication. Can anybody help me with some tutorial link. In google I found code only in spring framework, But I am not using Spring. I am looking for code to call API with basic authentication.
I have to add new url with authentication in the below code. What modification is required if API is secured with basic auth and it is POST method. I am new to java so not much aware.
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.Proxy;
import java.net.URL;
import java.net.URLConnection;
public class NetClientGet {
public static void main(String[] args) {
try
{
System.out.println("Inside the main function");
URL weburl=new URL("http://dummy.restapiexample.com/api/v1/employees");
HttpURLConnection conn = (HttpURLConnection) weburl.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/json");
System.out.println("Output is: "+conn.getResponseCode());
System.out.println("Output is: ");
System.setProperty("http.proxyHost", null);
//conn.setConnectTimeout(60000);
if(conn.getResponseCode()!=200)
{
System.out.println(conn.getResponseCode());
throw new RuntimeException("Failed : HTTP Error Code: "+conn.getResponseCode());
}
System.out.println("After the 2 call ");
InputStreamReader in=new InputStreamReader(conn.getInputStream());
BufferedReader br =new BufferedReader(in);
String output;
while((output=br.readLine())!=null)
{
System.out.println(output);
}
conn.disconnect();
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
}
}
Basic Authentication
See the RFC #2617 section 2: Basic Authentication Scheme
Add Authentication header into the request. Here's an example:
String username = "john";
String password = "pass";
// ...
URL weburl=new URL("http://dummy.restapiexample.com/api/v1/employees");
HttpURLConnection conn = (HttpURLConnection) weburl.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/json");
// snippet begins
conn.setRequestProperty("Authorization",
"Basic " + Base64.getEncoder().encodeToString(
(username + ":" + password).getBytes()
)
);
// snippet ends
System.out.println("Output is: "+conn.getResponseCode());
POST Method
See this answer for more information about using POST method with HttpURLConnection.
I am trying to write a simple HttpClient program.
This is the first time I am working with HttpClient, I am quite confused which jars to include.
I have included the apache-httpcomponents-httpclient.jar and org.apache.commons.httpclient.jar with these ones when I create a HttpClient object I see different methods in the client object
package com.comverse.rht;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.URI;
import org.apache.commons.httpclient.URIException;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
public class HttpClientTest {
public static void main(String[] args) throws URIException {
URI url = new URI("http://www.google.com/search?q=httpClient");
HttpClient client = new HttpClient();
GetMethod get = new GetMethod();
PostMethod post = new PostMethod();
String responseString;
StringBuilder sb = new StringBuilder();
String line;
// add request header
get.setURI(url);
get.addRequestHeader("User-Agent", "shaiksha429");
try {
int respCode = client.executeMethod(get);
System.out.println("Response Code:" +respCode);
System.out.println(
"PCRF HTTP Status" + HttpStatus.getStatusText(respCode)
);
responseString = get.getResponseBodyAsString();
BufferedReader rd = null;
rd = new BufferedReader(
new InputStreamReader(get.getResponseBodyAsStream())
);
while ((line = rd.readLine()) != null) {
sb.append(line + '\n');
}
System.out.println(sb);
} catch (HttpException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
But when I google I see a different example as below. What is the difference between the two? Why one HttpClient has "execute" and the other has "executeMethod". Which one I need to use?
String url = "http://www.google.com/search?q=httpClient";
HttpClient client = HttpClientBuilder.create().build();
HttpGet request = new HttpGet(url);
// add request header
request.addHeader("User-Agent", USER_AGENT);
HttpResponse response = client.execute(request);
System.out.println("Response Code : " + response.getStatusLine().getStatusCode());
BufferedReader rd = new BufferedReader(
new InputStreamReader(response.getEntity().getContent())
);
StringBuffer result = new StringBuffer();
String line = "";
while ((line = rd.readLine()) != null) {
result.append(line);
}
There were a lot of changes from HttpClient version 3 to version 4. The second example is definitely from HttpClient 4, so the first example is probably from the previous version.
Here is code that will do your google search, and read the result into a string
PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();
connectionManager.setMaxTotal(60);
connectionManager.setDefaultMaxPerRoute(6);
try (CloseableHttpClient client = HttpClients.custom().setConnectionManager(connectionManager).build()) {
HttpGet request = new HttpGet("http://www.google.com/search?q=httpClient");
request.setHeader("User-Agent", "HttpClient");
try (CloseableHttpResponse response = client.execute(request)) {
MediaType mediaType = MediaType.parseMediaType(response.getFirstHeader("Content-Type").getValue());
Charset charSet = mediaType.getCharSet();
HttpEntity entity = response.getEntity();
InputStream is = entity.getContent();
String body = CharStreams.toString(new InputStreamReader(is, charSet));
System.out.println("body = " + body);
EntityUtils.consume(entity);
}
}
First, you probably want to create a connection pool, so you can reuse the connection if you send multiple requests to the same server. The pool is typically created during application initialisation , for instance as a Spring singleton bean.
Here I used the ClosableHttpClient because it works with resource-try syntax, and you need to close both the httpClient, the response and the inputStream when you are done reading. The HttpClient is actually a lightweight object, the state like socket connection and cookies are stored elsewhere.
I use Spring's MediaType.parseMediaType() to get the char encoding, and Guavas CharStreams to convert the inputStream to a String. In my case google encoded the content using latin-1, because "search" is "søgning" in Danish.
The last step is to use EntityUtils.consume(entity), to ensure that all entity data has been read. If you use connection pooling this is important, because unread data will cause the connection to be thrown away, instead of being reused by the connection manager (this is extremely important if you are using https).
You're using a library whose interface has changed across its major versions. You can't casually copy jars and copy/paste examples without understanding which release you're using and which release an example or snippet was from.
Look at the examples that accompany the latest release and take anything old with a grain of salt.
Apache seems to move especially fast.
I am trying to Connect to url using URLConnection, in java with username and password.
This is the following code I am using:
package com.nivi.org.client;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import com.sun.jersey.core.util.Base64;
public class GetURLContent {
public static void main(String[] args) {
URL url;
try {
url = new URL("http://sampleurl.co.uk");
URLConnection conn = url.openConnection();
String username = "username";
String password = "password";
String Token = "zzzzzzzzzzzzzzzzzzzzz";
System.setProperty("http.proxyHost", "proxyhostname");
System.setProperty("http.proxyPort", "8080");
String userpass = username + ":" + password;
String basicAuth = "Basic " + new String(new Base64().encode(userpass.getBytes()));
conn.setRequestProperty ("Authorization", basicAuth);
conn.setRequestProperty ("Token", Token);
BufferedReader br = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
System.out.println("br............."+br.toString());
br.close();
System.out.println("Done");
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
=======================================
I am getting the following error
java.io.IOException: Server returned HTTP response code: 403 for URL:
http://sampleurl.co.uk
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1625)
at com.nivi.org.client.GetURLContent.main(GetURLContent.java:63)
=======================================
First of all my question is
Are these following lines in the code are correct?
conn.setRequestProperty ("Authorization", basicAuth);
conn.setRequestProperty ("Token", Token);
Are these following lines in the code are correct?
It depends on how the actual website you are accessing implements its user authentication.
What you appear to be doing is a combination of HTTP Basic Authentication (i.e. the Authorization header), and something involving a non-standard header called Token. This may be sufficient, if the website supports Basic Authentication.
You should probably read the website's programmer documentation of how their web APIs work. If there isn't any such documentation available to you, use your browsers web development tools to identify the mechanism that the site is using when you log in via a web browser ... and attempt to get your client to behave the same way.
One thing to note is that sending a Basic authorization response in an HTTP request is insecure. Use an HTTPS request if that is an option.
I'd like to use http://www.imdbapi.com/ in Java, but I don't know I can access the http response. I tried the following:
public Map<String, String> get(String title)
{
URL url = new URL("http://www.imdbapi.com/?t=" + title);
URLConnection conn = url.openConnection();
conn.getContent();
}
You can use URLConnection#getInputStream():
InputStream input = conn.getInputStream();
// ...
Or just the shorthand URL#openStream() directly:
InputStream input = url.openStream();
// ...
Once having it, just send it to a JSON parser of your choice, such as for example Gson:
InputStream input = new URL("http://www.imdbapi.com/?t=" + URLEncoder.encode(title, "UTF-8")).openStream();
Map<String, String> map = new Gson().fromJson(new InputStreamReader(input, "UTF-8"), new TypeToken<Map<String, String>>(){}.getType());
// ...
(note that I fixed your query string to be properly URL encoded)
See also:
Using java.net.URLConnection to fire and handle HTTP requests
Converting JSON to Java
When you go the website and type in the sample movie (i did True Grit ) you are actually able to see the response you would be getting. It looks something like this:
{"Title":"True Grit","Year":"2010","Rated":"PG-13","Released":"22 Dec 2010","Genre":"Adventure, Drama, Western","Director":"Ethan Coen, Joel Coen","Writer":"Joel Coen, Ethan Coen","Actors":"Jeff Bridges, Matt Damon, Hailee Steinfeld, Josh Brolin","Plot":"A tough U.S. Marshal helps a stubborn young woman track down her father's murderer.","Poster":"http://ia.media-imdb.com/images/M/MV5BMjIxNjAzODQ0N15BMl5BanBnXkFtZTcwODY2MjMyNA##._V1._SX320.jpg","Runtime":"1 hr 50 mins","Rating":"8.0","Votes":"51631","ID":"tt1403865","Response":"True"}
After knowing this info, you can easily parse your InputStream, which you obtain from your connection.
Good luck!
The below code should get you started. You need to add URL encoding if you are going to send special characters. In-order to parse JSON response you could probably use parser available in java at [link] http://www.JSON.org/
package problem;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;
public class Test {
public static void main(String args[])
{
BufferedReader rd;
OutputStreamWriter wr;
try
{
URL url = new URL("http://www.imdbapi.com/?i=&t=dexter");
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
wr = new OutputStreamWriter(conn.getOutputStream());
wr.flush();
// Get the response
rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = rd.readLine()) != null) {
System.out.println(line);
}
}
catch (Exception e) {
System.out.println(e.toString());
}
}
}
I recomend use http-request built on apache http api.
private static final HttpRequest<Map<String, String>> HTTP_REQUEST =
HttpRequestBuilder.createGet("http://www.imdbapi.com/",
new TypeReference<Map<String, String>>{}
).build();
public Map<String, String> get(String title) {
ResponseHandler<Map<String, String>> responseHandler = HTTP_REQUEST.execute("t", title);
return responseHandler.orElse(Collections.emptyMap()); //returns response parsed as map or empty map when response body is empty
}