Android persistent HttpClient connection - android

Would it be possible to setup an HttpClient such that on a website that updates periodically, perhaps due to AJAX, the resulting changes would be captured by the HttpClient. Similar to keeping a connection to a website alive, and if there were an update, the HttpClient would send the updated response to a listener of some type. I feel as if there is an obvious answer to my question, but I just haven't found it because I may have some of my terminology wrong...
This is just an example snippet of how I usually set up a connection:
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
HttpResponse response = httpClient.execute(httpGet);

Welcome to Stack Overflow! I do not think keeping a constant connection open to your site would be the best solution. Why don't you just poll every once in awhile?

Related

Accept Cookie from domain

I am trying to connect to foodEssentials API and it sends a cookie.
I am getting the error of Cookie rejected: "BasicClientCookie ..."
How do I deal with cookies coming in or is there any examples as I have looked around and found this loopj
I am not sure what I should do. Does the browser handle the cookie or the application?
Browsers handle server side cookies by themselves.
In case of Android application, developer need to explicitly handle the cookies.
Here is an example of handling cookies : http://svn.apache.org/repos/asf/httpcomponents/httpclient/trunk/httpclient/src/examples/org/apache/http/examples/client/ClientFormLogin.java
You can use the CookieStore class of Apache http client. Somewhere in your code initialization, create a cookie store and http context:
BasicCookieStore cookieStore = new BasicCookieStore();
httpContext = new BasicHttpContext();
httpContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
The cookie store will manage all the cookies as long as httpContext is alive.
So later, when doing a request, you just give the context to the httpClient:
AndroidHttpClient httpClient = AndroidHttpClient.newInstance(httpAgent);
HttpGet request = new HttpGet(url);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String json = httpClient.execute(request, responseHandler, httpContext);
... and the cookies will be properly managed.
See Android Http Client and Basic Cookie Store.

What exactly these lines do individually and collectively in JSON parsing

I am wondering after I searched in few books and on web that none of then detailed about it. I want to know that what exactly the purpose of below line individually while we parse JSON response file :
Lines ARE :
DefaultHttpClient client=new DefaultHttpClient();
HttpPost post = new HttpPost(Url);
HttpResponse response = client.execute(post);
HttpEntity entity = response.getEntity();
I know one thing that all together these four lines perform the connection with the server, but have no idea what individually the do.
I am sure I will get answer here from one of SOF besties.
Android's DefaultHttpClient Supports:
HTTPS, streaming uploads and downloads, configurable timeouts, IPv6 and connection pooling.
HttpPost :
The POST method is used to request that the origin server accept the entity enclosed in the request as a new subordinate of the resource identified by the Request-URI in the Request-Line.
HttpResponse :
Takes care of the response that is got after executing client.execute(post);
Finally the following code obtains the message entity of this response.
response.getEntity()
Please check the android documentation for detailed implementation.
Code above is resposible for Http post request to server and get JSON response, so that you can parse and get required data.
Above 4 lines don't do JSON parsing. They only make an HTTP connection and the way of doing it is only recommended below Gingerbread. For Gingerbread and above use HttpURLConnection. More details here.
After you have the content (make a check if the response code is as expected - 200 or 201) you can proceed to JSON parsing. Use either Jackson, GSON or Android's json framework (this is my preferred order).
As per may Opinion
DefaultHttpClient client=new DefaultHttpClient(); responsible for HttpsURLConnection efficient(Connection) when connecting to up-to-date servers, without breaking compatibility with older ones.
HttpPost post = new HttpPost(Url); responsible for get POST request and send response.
HttpResponse response = client.execute(post); responsible for executes HTTP request using the default context.
HttpEntity entity = response.getEntity(); responsible for carry a content entity associated with the request or response.
For more information go to:http://hc.apache.org/httpcomponents-client-ga/tutorial/html/fundamentals.html

Genymotion unable to connect to server?

I have an app that sends a http request to a server and receives a JSON for processing. I test it on both a physical device and Genymotion.
The app runs fine on the physical device but on Genymotion throws NetworkOnMainThreadException.
I tracked the exception and this is the part with the issue:
..
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params,"UTF-8"));
// Exception on this line:
HttpResponse httpResponse = httpClient.execute(httpPost);
//
HttpEntity httpEntity = httpResponse.getEntity();
...
It seems that the Genymotion can't connect to server to execute the request. But its browser loads the sites just fine.
So, anyone knows what's going wrong here?
I found what the problem was:
As explained in this answer, since API 11, the NetworkOnMainThreadException is thrown to inform using long-running tasks (like http communications) in the main thread.
By using AsyncTask the problem was resolved and everything worked as it should.

dfference between using URLCOnnection Object and Httppost in android client

I am using URLConnection Object to send data from my android client to server.
URL url = new URL("http://10.0.2.2:8080/hello");
URLConnection connection = url.openConnection();
connection.setDoOutput(true);
ObjectOutputStream out=new ObjectOutputStream(connection.getOutputStream());
String s="check"+","+susername;
out.writeObject(s);
out.flush();
out.close();
But I have seen many android programs sending data using httppost in the following way.
HttpClient client=new DefaultHttpClient();
HttpPost httpPost=new HttpPost(LOGIN_ADDRESS);
List pairs=new ArrayList();
String strUsername=username.getText().toString();
String strPassword=password.getText().toString();
pairs.add(new BasicNameValuePair("username", strUsername));
pairs.add(new BasicNameValuePair("password", strPassword));
httpPost.setEntity(new UrlEncodedFormEntity(pairs));
HttpResponse response= client.execute(httpPost);
please explain the differnce between the two. How would you receive the data in the later case in a servlet. please give a brief explanation on this HttpPost. In the internet all I find is code. pls give a step by step explanation on HttpPost and its methods and how should the data be received in the servlet. Links will do fine.
This blog post does a pretty good job of explaining the difference between the two of them (well actually HttpURLConnection, but that's just a subclass of URLConnection). Some highlights from the article are:
HttpURLConnection easily allows gzip encoding
HttpURLConnection can allow for easy caching of results
HttpURLConnection is newer and being actively developed on so it's only going to get faster and better
HttpURLConnection has some annoying bugs on foryo and pre-froyo platforms
HttpClient is tried and true. It's been around for a long time and it works
HttpClient is pretty much not being developed on because it's so old and the API is completely locked down. There isn't much more the android developers can do in terms of making it better.
While the end of the article recommends use of HttpURLConnection on all platforms above froyo, I personally like using HttpClient no matter what. It's just easier to use for me and makes more sense. But if you're already using HttpURLConnection, you should totally keep using it. It's going to be receiving lot's of love from the android developers from here-on-out.

See entire POST request from Android app

I'm trying to debug a little problem I have with a web service. I cannot POST to the webservice, but I can GET just fine.
When I try to post data to the webservice I get a HTTP 1/1 400 Bad Request.
Is there a way I can see more details?.. I dont have access to the server, on which the webservice is hosted
HTTP Post code
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://lino.herter.dk/Service.svc/Data/");
StringBuilder sb = new StringBuilder();
StringEntity se = new StringEntity("test");
se.setContentType("text/xml");
httppost.setHeader("Content-Type","text/xml");
httppost.setEntity(se);
HttpResponse response2 = httpclient.execute(httppost);
sb = inputStreamToString(response2.getEntity().getContent());
It might be easiest to set up Wireshark on your development machine, and capture the traffic between your Android and the server. You'll have to run Wireshark in Promiscuous mode, which I think is the default option.

Categories

Resources