I want to send a http request via a virtual interface. I'm able to do it with Apache Http-Client :
HttpClient client = new DefaultHttpClient();
HttpParams params = client.getParams();
params.setParameter(ConnRoutePNames.LOCAL_ADDRESS, InetAddress.getByName("192.168.10.20"));
How can I do this in Jetty's Http-Client?
Docs for the Jetty client are here with plenty of examples:
http://www.eclipse.org/jetty/documentation/current/http-client-api.html
Related
I am using Jetty to develop my client application side.
I am not using Jetty in the server part.
What I need to configure on the client side to be able send "https" request using the Jetty client?
That is what I do for HTTP client:
httpClient = new HttpClient();
// Configure HttpClient
httpClient.setFollowRedirects(false);
httpClient.start();
Request request = httpClient.newRequest(url);
//code
httpClient.stop();
I got this exception if I try to send request using "https":
java.util.concurrent.ExecutionException: java.lang.NullPointerException
at org.eclipse.jetty.client.util.FutureResponseListener.getResult(FutureResponseListener.java:118)
at org.eclipse.jetty.client.util.FutureResponseListener.get(FutureResponseListener.java:101)
at org.eclipse.jetty.client.HttpRequest.send(HttpRequest.java:653)
at egm.httpClient.jetty.TestBackend.POST(TestBackend.java:204)
at egm.httpClient.jetty.TestStep.execute(TestStep.java:77)
at egm.httpClient.jetty.TestSuite.execute(TestSuite.java:57)
at egm.httpClient.jetty.TestLauncher.main(TestLauncher.java:139)
Caused by: java.lang.NullPointerException
at org.eclipse.jetty.io.ssl.SslClientConnectionFactory.newConnection(SslClientConnectionFactory.java:57)
at org.eclipse.jetty.client.AbstractHttpClientTransport$ClientSelectorManager.newConnection(AbstractHttpClientTransport.java:187)
at org.eclipse.jetty.io.ManagedSelector.createEndPoint(ManagedSelector.java:411)
at org.eclipse.jetty.io.ManagedSelector.access$1600(ManagedSelector.java:56)
at org.eclipse.jetty.io.ManagedSelector$CreateEndPoint.run(ManagedSelector.java:587)
at org.eclipse.jetty.util.thread.strategy.ExecuteProduceConsume.produceAndRun(ExecuteProduceConsume.java:213)
at org.eclipse.jetty.util.thread.strategy.ExecuteProduceConsume.execute(ExecuteProduceConsume.java:101)
at org.eclipse.jetty.io.ManagedSelector.run(ManagedSelector.java:136)
at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:654)
at org.eclipse.jetty.util.thread.QueuedThreadPool$3.run(QueuedThreadPool.java:572)
at java.lang.Thread.run(Unknown Source)
Since jetty-client >= 10
HttpClient supports HTTPS requests out-of-the-box like a browser does.
Prior jetty-client 9
In order to perform HTTPS requests, you should create first a SslContextFactory.Client
You have to pass a SslContextFactory into the HttpClient like this:
HttpClient httpClient = new HttpClient(new SslContextFactory());
You can even configure the SslContextFactory by trusting all or give it a keystore:
new SslContextFactory(true);
new SslContextFactory("/path/to/.keystore");
this is what worked for me with jetty-11
SslContextFactory.Client sslContextFactory = new SslContextFactory.Client();
sslContextFactory.setTrustAll(true); // you might want to think about this first
ClientConnector clientConnector = new ClientConnector();
clientConnector.setSslContextFactory(sslContextFactory);
HttpClient httpClient = new HttpClient(new HttpClientTransportDynamic(clientConnector));
httpClient.start();
for explanation, check out the official documentation here https://www.eclipse.org/jetty/documentation/jetty-11/programming-guide/index.html#pg-client-http-configuration-tls
I have a protected resource which requires me to login. Im using the commons client with the following code block.
HttpClient httpClient = new HttpClient();
httpClient.getParams().setParameter("http.protocol.cookie-policy", CookiePolicy.BROWSER_COMPATIBILITY);
httpClient.getParams().setParameter("http.protocol.single-cookie-header", Boolean.TRUE);
PostMethod postMethod = new PostMethod("/admin/adminlogon.do");
postMethod.setRequestEntity(new StringRequestEntity("action=logon&adminUser=admin&adminPassword=password",
"application/x-www-form-urlencoded",
"UTF-8"));
postMethod.addParameter("action","logon");
postMethod.addParameter("adminUser","admin");
postMethod.addParameter("adminPassword","password");
httpClient.executeMethod(postMethod);
String response2 = postMethod.getResponseBodyAsString();
Above is where I basically login. This works fine im getting a nice little JSESSIONID cookie back.
GetMethod get = new GetMethod("/admin/api.do?action=getSomeJson");
httpClient.executeMethod(get);
When I check the logic on the sever the for the 2nd request I notice that we are using a different JSESSIONID. Therefore the get seems to fail to log in. I was under the impression the httpClient managed the cookies and sent the same cookie back. When I log into my app normally through the UI I see the same cookie in each request just not in the this test code.
String s = get.getResponseBodyAsString();
get.releaseConnection();
Do I need to do something with the httpClient to ensure it uses the same cookies from the first post request when it does its get request??
Thanks in advance.
Your assumption regarding HTTP client cookie behavior is correct.
In your case your not use the same httpClient instance. To fix it you need to allocate the httpClient only once (in PostConstructor):
httpClient = new DefaultHttpClient(); // or new HttpClient();
Then, you perform your calls using the same instance of the client. The client will take a cookie from a response, will store it in the cookieStore and will send it with the next request.
[Added after the comment]
The following code works for me:
httpClient = new DefaultHttpClient();
// Create a local instance of cookie store
cookieStore = new BasicCookieStore();
// Set the store
httpClient.setCookieStore(cookieStore);
I have a REST webservice with some methods.
I'm sending requests to the rest with Apache HttpClient 4.
When I make a connection to this rest, in a method that is bigger and slower, it throws a NoHttpResponseException.
After googling, I discovered that the server is cutting down the connection with my client app.
So, I tried to disable the timeout this way :
DefaultHttpClient httpclient = null;
HttpParams params = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(params, 0);
HttpConnectionParams.setSoTimeout(params, 0);
HttpConnectionParams.setStaleCheckingEnabled(params, true);
httpclient = new DefaultHttpClient(params);
httpclient.execute(httpRequest, httpContext);
But it failed. The request dies in 15 seconds (possible default timeout?)
Does anyone know the best way to do this?
I would suggest that you return data to the client before the timeout can occur. This may just be some bytes that says "working" to the client. By trickling the data out, you should be able to keep the client alive.
My simple Apache HttpClient (4.0.1) client application makes an HttpGet request to a server URL in the main() method and prints the response. On startup, the application registers an implementation of java.net.CookieHandler in a static block.
On checking the cookies received on the server side, I found that the cookies are not being received by the Server when the HttpClient makes the GET request.
On the other hand, when I replaced the Apache HttpClient with a plain java.net.URL(HTTP_URL).openStream(), the cookies were set by the CookieHandler on the Request and were received by the Server.
Is it that CookieHandler does not work with Apache HttpClient?
Code:
Client.java
static {
CookieHandler.setDefault(new CookieHandler() {
public Map get(URI u, List r) {
return Collections.singletonMap("Cookie",
Collections.singletonList(COOKIE_STRING));
}
});
}
Using HttpClient (does not put cookies on request)
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet(HTTP_URL);
client.execute(get);
Using java.net.URL (sets the cookies on request)
URL url = new URL(HTTP_URL);
InputStream is = url.openStream();
Is it that CookieHandler does not work with Apache HttpClient?
That is correct.
The Apache HttpClient codebase uses its own cookie and cookie store representations / mechanisms. Here is a link to the relevant section of the HttpClient tutorial. (It is pretty sketchy, but if you look at the javadocs for the relevant classes, you should be able to figure out how to use it.)
(If you are using an older version of Apache HttpClient, beware that the APIs have changed significantly.)
I want to set the HTTP Request header "Authorization" when sending a POST request to a server.
How do I do it in Java? Does HttpClient have any support for it?
http://www.w3.org/Protocols/HTTP/HTRQ_Headers.html#z9
The server requires me to set some specific value for the authorization field:
of the form ID:signature which they will then use to authenticate the request.
Thanks
Ajay
Below is the example for setting request headers
HttpPost post = new HttpPost("someurl");
post.addHeader(key1, value1));
post.addHeader(key2, value2));
Here is the code for a Basic Access Authentication:
HttpPost request = new HttpPost("http://example.com/auth");
request.addHeader("Authorization", "Basic ThisIsJustAnExample");
And then just an example of how to execute it:
HttpParams httpParams = new BasicHttpParams();
HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1);
HttpConnectionParams.setConnectionTimeout(httpParams, 3000);
HttpClient httpclient = null;
httpclient = new DefaultHttpClient(httpParams);
HttpResponse response = httpclient.execute(request);
Log.d("Log------------", "Status Code: " + response.getStatusLine().getStatusCode());
This question is "answered" here:
Http Basic Authentication in Java using HttpClient?
There are many ways to do this. It was frustrating for me to try to find the answer. I found that the best was the Apache docs for HttpClient.
Note: answers will change over time as the libraries used will have deprecated methods.
http://hc.apache.org/httpcomponents-client-4.5.x/tutorial/html/authentication.html