Client hangs when passing cookies between DefaultHttpClients - java

I have a strange problem I have been trying to solve for the last two days, and seem to have narrowed it down to the cookies attached to the global DefaultHttpClient variable associated with my application.
When I use the client with post params, everything hangs after the first time it is used. I don't get any requests to my server, the application just refuses to do anything. If there are no post parameters, everything works just fine. Here is the applicable code.
httppost.setEntity(new UrlEncodedFormEntity(pairs,"UTF-8"));
DefaultHttpClient defhttpClient = new DefaultHttpClient();
logger.info("URL Encoded");
//When I pass the cookies things stop working...
//defhttpClient.setCookieStore(httpclient.get_cookies());
response = defhttpClient.execute(httppost);
logger.info("Received response");
If I make a new DefaultHttpClient and run the post request with parameters, the client can talk to the server just fine. The only problem is that I need the cookies from the old client to tell the server who the current user is. When I take the cookies from my old client and give them to my new one, the application hangs. Again, I dont even see a request coming into my server.
Does anyone have any idea what's going on here?

Alright, so I couldn't figure out how to do this by sending the message in the body with setentity. Just decided to put the json data in the header instead and everything seems to work fine. Not really too big of a problem. Would have preferred to do it the right way, but sometimes you can't get everything you want. Here is the code for anyone with the same problem.
JSONObject post_params = new JSONObject();
for(NameValuePair pair : pairs){
post_params.put(pair.getName(), pair.getValue());
}
httppost.setHeader("json",post_params.toString());
response = httpclient.get_client().execute(httppost);

Related

Migrate OOB in HTTP POST request to googleapis

We are making use of this end point - https://www.googleapis.com/oauth2/v4/token
to get the access token.
We make use of apace HTTP classes to make a POST request to this end point in this way -
HttpPost httpPost = new HttpPost(GET_ACCESS_TOKEN_API);
StringBuilder blr = new StringBuilder().append(CLIENT_ID).append("=")
.append((String) accountCredentials.get(CLIENT_ID)).append("&")
.append(CLIENT_SECRET).append("=")
.append((String) accountCredentials.get(CLIENT_SECRET))
.append("&").append(REFRESH_TOKEN).append("=")
.append((String) accountCredentials.get(REFRESH_TOKEN))
.append("&grant_type=refresh_token")
.append("&redirect_uri=urn:ietf:wg:oauth:2.0:oob");
// The message we are going to post
StringEntity requestBody = new StringEntity(blr.toString());
// the default content-type sent to the server is
// application/x-www-form-urlencoded.
requestBody.setContentType("application/x-www-form-urlencoded");
httpPost.setEntity(requestBody);
// Make the request
HttpResponse response = HttpUtils.getHttpClient().execute(httpPost);
There has been a recent intimation from google to migrate from out-of-band as they have plans to deprecate this.
We make use of it this way as you can see in the code above -append("&redirect_uri=urn:ietf:wg:oauth:2.0:oob");
GET_ACCESS_TOKEN_API is https://www.googleapis.com/oauth2/v4/token.
I saw some posts mentioning that we have to replace this redirect_uri to localhost.
Can someone explain exactly how this works and what change needs to be done to migrate this successfully ? I tried searching through the documentation to see if there any sample examples but couldn't find anything that matches our use case.
I am referring to this site -
https://developers.google.com/api-client-library/java/google-oauth-java-client/support
I tried to browse through samples, guides, but it mostly talks about different API's. I didn't find the github links that much useful.
Any help would be much appreciated.

HttpRequestHandler - How to tell client to save a cookie?

I'm in a journey of making a simple HTTP server using Java for educational purposes. I need to know how to instruct a client to save a cookie for identifying its session ID.
I've done my research and stumbled upon this and this which, despite being greatly informative and in fact introduced me to the whole CookieStore thing, does not really specify how to tell the client to save a cookie.
From what I've come to understand, the handle method in HttpRequestHandlers has only three parameter passed to it:
HttpRequest - the request itself along with some information about it.
HttpResponse - the "medium" as of where the response should be writen upon.
HttpContext - ... (Not really sure what it does, TBH.)
Meanwhile, all of the answers in the links I've stated above would call
response = client.execute(httppost, localContext);, or
HttpResponse response1 = httpClient.execute(method1, httpContext);
..at some point of the handling. I've no idea on how one could get a reference to the client (and thus execute the request to store the cookie).
What should I do? Am I missing something?
Cookie userCookie = new Cookie("Name","Value");
userCookie.setMaxAge(-1);//for a session cookie
userCookie.setPath("/");
response.addCookie(userCookie);//adds to cookie to the response that is sent to the browser.

Java: wait to receive a value from another server (by http?)

I am developing a web application with struts2&spring3 and one of the last things I need to do is the communication between my server and another server where I have to send a XML file and after wait for its response.
As someone said me, I have implemented the sending of the XML file by HTTP with the library HttpClient4 (from Apache):
File file = new File(fileName);
FileEntity entity = new FileEntity(file, "text/xml; charset=\"UTF-8\"");
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPost method = new HttpPost(server);
method.setEntity(entity);
HttpResponse response = httpclient.execute(method);
But now I have to implement the waiting and getting of the response that the other server will send me. The problem is that the other server is still not developed, so, which way you think it would be the best to get that answer? by HTTP also would be perfect but I don't know which library and how to do it.
Thank you very much in advance for all your help,
Aleix
Here I find two options
Send response immediately.
Develop a module [client side] which accepts response from server after request is received and added to queue [ Asynchronous mode ]

Multiple Difficulties with HttpURLConnection class in Java for Android

--Update--
Apologies for those who helped me, it turns out this is just a problem with Eclipse's debugger. After suspecting that it was leading me wrong, I placed down a couple of System.out.println to watch the variables, and according to them they ARE being changed, and that the debugger was just showing me old information for whatever reason. No clue why that's happening, but the important thing is that the code does apparently actually work.
I'm working on a method to share with twitter for an Android application, and I'm having errors when setting up the HttpURLConnection. I create the connection object as per usual, using the openconnection function of a url then casting it to a HttpURLConnection, and when I subsequently run SetRequestMethod("POST") on the connection, it does absolutely nothing. When I run the code in the debugger line by line, as I go through that line the request method just remains as the default ("GET"). Anyone have any idea as to why this may be happening? I'm getting the same problem with setDoOutput(true) also not changing anything. However, adding a request property does still work. I've been searching around and haven't been able to find anything on this problem, not even another person reporting these problems.
I am not sur whether using HttpURLConnection is the best here.
Did you try the following way?
// Building the POST request
final BasicNameValuePair message = new BasicNameValuePair("yourField", "yourContent");
final List<NameValuePair> list = new ArrayList<NameValuePair>(1);
list.add(message);
final HttpPost httppost = createHttpPost(UrlEncodedFormEntity(list));
// Building the HTTP client
final HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, YOUR_CHOSEN_CONN_TIMEOUT);
HttpConnectionParams.setSoTimeout (httpParameters, YOUR_CHOSEN_SO_TIMEOUT);
final HttpClient httpClient = new DefaultHttpClient(httpParameters);
// Execution of the POST request
final HttpResponse response = httpClient.execute(httppost);
This is the way I usually do, with no problems.
[EDIT: 04-25-2014] Apache's HttpClient was the best approach for Froyo and former versions. Now, according to this article from Android Developers Blog (written after this Q&A), it is better to use URLConnection.

How to use HttpClient to download continous data stream?

I'm currently using HttpURLConnection to stream live content such as a radio broadcast. However it seems that using HttpClient is a better option since it's well supported by Android and it's a better implementation. Also, there seems to be a logic for automatic reconnection from a lost connection.
My problem is that I can't get this to work. It's always hanging when calling httpclient.execute(...).
What am I doing wrong?
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet("http://208.76.243.123:7100");
HttpResponse response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
Run it in debugger and when it hangs, call break. Then find the thread that is executing your code and see in stack trace where exactly it blocked. You will see if it blocked on IO or something else is happening. With that data it will be easier to identify the problem.
Are you sure your server understands the HTTP protocol? (I assume yes, it sounds like you had a different client working). It is possible the execute method is blocking because it has not seen a valid Response header yet.
You probably want entity.getContent() which will return a handle to a stream. See this question.

Categories