Is there any way I can access RESTful webservice using a servlet. I dont want to use Jersey client?
EDIT: How can I pass object in the url and make sure that marshalling/unmarshalling is done properly?
You can use the commons-httpclient library (http://hc.apache.org/httpcomponents-client-ga/) to make a request to your REST service, and gson (http://code.google.com/p/google-gson/) to serialize/deserialize java objects to JSON
You could code your own HTTP requests e.g. using HTTPURLConnection. Here you can set the request method and change the URL or/and body as appropiate e.g.
URL url = new URL("http://www.example.com/resource");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
// etc
This way you're just using the standard java.net API.
You don't need to use jersey client, it's just a URL, you can use:
new URL("http://locationofservice").openConnection();
Related
I am trying to consume a RESTFUL web service using Java(HttpURLConnection and InputStream).I am able to print the response using BufferedReader, but it returns a response header as well and the format is causing issues to convert it to a Java POJO.
I tried using a URLConnection and then retrieving the input stream and passing it to the ObjectMapping(provided by Jackson)
final URL url = new URL("url");
final HttpURLConnection uc = (HttpURLConnection) url.openConnection();
uc.setRequestMethod("GET");
final ObjectMapper objectMapper = new ObjectMapper();
MyData myData = objectMapper.readValue(uc.getInputStream(), MyData.class);
Error Message : "No content to map due to end-of-input\n"
In your code you don't show where you actually read the data and where you declared and filled your output variable. As code is now it seems to be the incorrect reading from your rest service. But instead of writing your own code to read fro rest url I would suggest to use the 3d party library that does it for you. Here is few suggestions: Apache Http Client, OK Http client and finally my favorite - MgntUtils Http Client (library written and maintained by me) Here is the HttpClient javadoc, Here is the link to The latest Maven artifacts for MgntUtils library and here MgntUtils Github link that contains library itself with sources and javadoc. Choose some Http Client and read the content using that client and then you can use the content.
I am pretty new concerning REST api and POST request.
I have the url of a REST api. I need to access to this api by doing an API call in JAVA thanks to a client id and a client secret (I found a way to hash the client secret). However, as I am new I don't know how to do that api call. I did my research during this all day on internet but I found no tutorial, website or anything else about how to do an api call. So please, does anyone know a tutorial or how to do that? (if you also have something about POST request it would be great)
I would be very thankful.
Thank you very much for your kind attention.
Sassir
Here's a basic example snippet using JDK classes only. This might help you understand HTTP-based RESTful services a little better than using a client helper. The order in which you call these methods is crucial. If you have issues, add a comments with your issue and I will help you through it.
URL target = new URL("http://www.google.com");
HttpURLConnectionconn = (HttpURLConnection) target.openConnection();
conn.setRequestMethod("GET");
// used for POST and PUT, usually
// conn.setDoOutput(true);
// OutputStream toWriteTo = conn.getOutputStream();
conn.connect();
int responseCode = conn.getResponseCode();
try
{
InputStream response = conn.getInputStream();
}
catch (IOException e)
{
InputStream error = conn.getErrorStream();
}
You can also use RestTemplate from Spring: https://spring.io/blog/2009/03/27/rest-in-spring-3-resttemplate
Fast and simple solution without any boilerplate code.
Simple example:
RestTemplate rest = new RestTemplate();
MultiValueMap<String, String> map = new LinkedMultiValueMap<String, String>();
map.add("firstParamater", "parameterValue");
map.add("secondParameter", "differentValue");
rest.postForObject("http://your-rest-api-url", map, String.class);
The Restlet framework also allows you to do such thing thanks to its class ClientResource. In the code below, you build and send a JSON content within the POST request:
ClientResource cr = new ClientResource("http://...");
SONObject jo = new JSONObject();
jo.add("entryOne", "...");
jo.add("entryTow", "...");
cr.post(new JsonRepresentation(jo), MediaType.APPLICATION_JSON);
Restlet allows to send any kind of content (JSON, XML, YAML, ...) and can also manage the bean / representation conversion for you using its converter feature (creation of the representation based on a bean - this answer gives you more details: XML & JSON web api : automatic mapping from POJOs?).
You can also note that HTTP provides an header Authorization that allows to provide authentication hints for a request. Several technologies are supported here: basic, oauth, ... This link could help you at this level: https://templth.wordpress.com/2015/01/05/implementing-authentication-with-tokens-for-restful-applications/.
Using authentication (basic authentication for example) can be done like this:
String username = (...)
String password = (...)
cr.setChallengeResponse(ChallengeScheme.HTTP_BASIC, username, password);
(...)
cr.post(new JsonRepresentation(jo), MediaType.APPLICATION_JSON);
Hope it helps you,
Thierry
I need to be able to use a password protected proxy and be able to read json information returned from a url.
I do not want to declare proxies at the system level; I would like to have multiple proxies being used in the same application.
What is the best way to do this?
I once faces the same problem. Unfortunately, JSoup is not a good choice for this. I ended up using the apache http client, which works nicely with proxies.
Here is the proxy-relevant part of my http-client configuration:
String ipStr = "the.proxy.ip.string";
int port = 8080;
String proxyLogin = "your login name";
String proxyPassword = "your password";
httpClient.getCredentialsProvider().setCredentials(
new AuthScope(ipStr, port),
new UsernamePasswordCredentials(proxyLogin, proxyPassword));
HttpHost httpHost = new HttpHost(ipStr, port, "http");
httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, httpHost);
You can use the http-client to get the website or JSON response from the net. If the content is HTML, you can use JSoup as parser with the returned input. If you get JSON back, then you probably want to use a JSON parser like json-simple (but there are many other very useful JSON libraries out there!)
I want to readLines from a URL, which resolves to an HTTP service. I can use
Resources.readLines(url, Charsets.SOMETHING)
from com.google.common.io.
This works, but the class javadoc for Resources states the following, without further explanation:
Note that even though these methods use URL parameters, they are usually not appropriate for HTTP or other non-classpath resources.
Why is this method inappropriate for reading from an HTTP service, and what is the recommended approach?
When using URL to send an HTTP request, the typical process is
URL url = new URL(someStringUrl);
HttpUrlConnection con = (HttpUrlConnection) url.openConnection();
// do some stuff with con, add headers, add request body, etc.
con.getInputStream(); // get body of response
The URL given to Resources skips all that. The methods in Resources depend on URL#openStream() which skips any modifications to the URLConnection, ie. is equivalent the url.openConnection().getInputStream(). It's possible you'll get any number of 400 level error codes from the HTTP response because your request wasn't correct.
This won't happen with class path resources because the protocol is simple. You just copy the bytes.
I'm writing class to read from a JSON web service using Jackson. Previously, when reading from a web service I've used a custom web browser class to be able to set certain connection information, such as proxy host/port/username/password, etc as well as read and connection timeout values.
Is there a way to do this in Jackson natively? E.g. by setting the proxy parameters in a configuration?
Or should I revert back to getting the API response as a string and then using Jackson to parse it?
FYI, this is the (simplified) code that I am using.
URL configUrl = new URL("http://my.webservice.com/api");
ConfigClass localConfig = mapper.readValue(configUrl, ConfigClass.class);
I would retrieve the api response as a Reader (or InputStream), and then use Jackson to parse that. Jackson just calls configUrl.openStream() under the hood, and there's no reason not to do that yourself.
I think you should do the latter, proxy support hasn't been added to Jackson.
Plus it's pretty simple, using the Proxy class.
Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("127.0.0.1", 8080));
URL url = new URL("URL");
HttpURLConnection uc = (HttpURLConnection)url.openConnection(proxy);
uc.connect();