How to use jackson with a web proxy - java

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();

Related

Consumption of a REST web service using URLConnection

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.

Restlet: Unable to find a converter for this representation : [application/repo.foo+xml]

I'm trying to retrieve a resource from web service, but get this warning:
WARNING: Unable to find a converter for this representation : [application/repo.foo+xml]
And my code returns null entity. Here is code
Engine.getInstance().getRegisteredClients().clear();
Engine.getInstance().getRegisteredClients().add(new HttpClientHelper(null));
Engine.getInstance().getRegisteredConverters().add(new JacksonConverter());
ClientResource resource = new ClientResource(path);
ChallengeScheme scheme = ChallengeScheme.HTTP_BASIC;
ChallengeResponse auth = new ChallengeResponse(scheme, "user", "password");
resource.setChallengeResponse(auth);
Repo entity = resource.get(Repo.class);
System.out.println(entity);
UPDATE
My attempts which unfortunately don't work:
resource.getRequestAttributes().put("org.restlet.http.headers", new MediaType("application", "application/repo.foo+xml"));
resource.setAttribute("Content-Type", "application/repo.foo+xml");
There is some confusion in your question.
You are writing a client. You can tell the client to set an accept header. Put simply, this is a hint to the server about what content type you'd like the response to be in. JSON, HTML, XML, whatever. The server can either honour this, send you it's best guess or ignore it completely.
You can try setting the accept header to "application/javascript" and see how it responds. If it continues to send "application/repo.foo+xml" then you will probably be able to parse it with the jackson xml databind package. You may have to register the media type and converter with the client so it knows which converter to use to serialise the object.

Java Web Proxy, Returning JSON object

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!)

How can I access a Restful webservice using servlet?

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();

Using Java, Need to establish an https connection via proxy

I need to establish and send/read over/from an https connection (to a website of course) but through an http proxy or SOCKS proxy. A few other requirements
supports blocking (I can't use non-blocking/nio)
isn't set as an environment or some other global scope property (there are multiple threads accessing)
I was looking into HttpCore components but I did not see any support for blocking https.
Look at the java.net.Proxy class. That does what you need. You create one, and then pass it to the URLConnection to create the connection.
To support per-thread proxy, your best bet is Apache HttpClient 4 (Http Components Client). Get the source code,
http://hc.apache.org/downloads.cgi
It comes with examples for both HTTP proxy and SOCKS proxy,
ClientExecuteProxy.java
ClientExecuteSOCKS.java
Did you look at Apache HTTP Client? Haven't used it in ages but I did use it to pick a proxy server dynamically. Example from site here:
HttpClient httpclient = new HttpClient();
httpclient.getHostConfiguration().setProxy("myproxyhost", 8080);
httpclient.getState().setProxyCredentials("my-proxy-realm", " myproxyhost",
new UsernamePasswordCredentials("my-proxy-username", "my-proxy-password"));
GetMethod httpget = new GetMethod("https://www.verisign.com/");
try {
httpclient.executeMethod(httpget);
System.out.println(httpget.getStatusLine());
} finally {
httpget.releaseConnection();
}
System.setProperty("http.proxyHost", "proxy.com");
System.setPropery("http.proxyPort", "8080");
URL url = new URL("http://java.sun.com/");
InputStream in = url.openStream();
http://java.sun.com/javase/6/docs/technotes/guides/net/proxies.html

Categories