HttpGet crashes app [duplicate] - android

This question already has answers here:
How can I fix 'android.os.NetworkOnMainThreadException'?
(66 answers)
Closed 8 years ago.
I am trying to get the HTML source from a URL in my Android app using the code below. However, it crashes at the line HttpResponse response = client.execute(request);. How can I fix this?
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(url);
HttpResponse response = client.execute(request);
String html = "";
InputStream in = response.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder str = new StringBuilder();
String line = null;
while((line = reader.readLine()) != null)
{
str.append(line);
}
in.close();
html = str.toString();
UPDATE! I am too new of a user to post my own official answer apparently, so here it is:
Thanks to both of you! Hichris' comments & links pointed me in the right direction. Here are the 3 hurdles that were causing the problem:
The AsyncTask should be placed in the same class file, but as a
sub-class (I might not have my terminology right there)
I was filling a text box with the resulting html code. However, I was doing that within the doInBackground() section of the AsyncTask when I should have been doing it in onPostExecute().
The urls I was passing to the AsyncTask were not properly converted to URI. This caused the program to crash for some urls but not others.

The best way to use for network call is Volley library check this link "https://developers.google.com/events/io/sessions/325304728".It is very simple and very easy to use. Check the below link for what are the problem in creating HTTPClient and other third party library for network call "https://www.youtube.com/watch?v=MIc4kl3yXw0&list=LLckOGLeNzdRsRG5CvBux_dg&index=8"

Related

Android HTTP request sometimes has no response, until opening the page on a computer

I'm having a very odd issue with getting data from a PHP script in Android. The below example seams to be what everyone suggests to use to get the data. And it works.. for a while. If you run it a couple of times it gets the scores perfectly. But if you wait an hour or two and then try again it will fail over and over again. Nothing actually "fails" though, I do have proper try catch around this and it runs in a Async task, it just returns nothing in the string. This will happen a hundred times, until I open the script on my computer. Then the script shows me the data and the very next time I open in on the phone, it works. Until a few hours later...
I have scoured the internet for the last week, trying ever different example of getting data from the page and they all do the same thing. I even though maybe it was the web-server we are on, so I moved to a new one, same issue.
If you need anymore details let me know. I can give you the PHP script if you think that will help. Although it happens with 5 different scripts that I have.
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
InputStream is = httpEntity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
Log(json);

Http Post Request in Android won't return appropriate data?

Okay, so I was trying to send Http Post Requests to this one site, and I sniffed the sent request with wireshark thus getting the text data from the post request of this site. I used this in a stock Java application, and it worked perfectly fine. I could use the post method regularly with no problem whatsoever, and it would return the appropriate website. Then I tried doing this with Android. Instead of returning the actual html data after executing the post request, it returns the regular page html data untouched. It DOES send a post request (sniff with wireshark again), it just doesn't seem to get the appropriate response. I took the exact same method used from another one of my projects, which worked perfectly fine in that project, and pasted it into my new project. I added the INTERNET user permission in Android, so there's nothing wrong with that. The only visible difference is that I used NameValuePairs in the other one (the one that worked) and in this one I'm directly putting the string into a StringEntity without encoding (using UTF-8 encoding screws up the String though). I used this exact same line of text in regular Java like I said, and it worked fine with no encoding. So what could be the problem? This is the code:
public static String sendNamePostRequest(String urlString) {
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(urlString);
StringBuffer sb = new StringBuffer();
try {
post.setEntity(new StringEntity(
"__EVENTTARGET=&__EVENTARGUMENT=&__VIEWSTATE=%2FwEPDwULLTE3NDM5MzMwMzRkZA%3D%3D&__EVENTVALIDATION=%2FwEWBAL%2B%2B4CfBgK52%2BLYCQK1gpH7BAL0w%2FPHAQ%3D%3D&_nameTextBox=John&_zoekButton=Zoek&numberOfLettersField=3"));
HttpResponse response = client.execute(post);
HttpEntity entity = response.getEntity();
BufferedReader br = new BufferedReader(new InputStreamReader(
entity.getContent()));
String in = "";
while ((in = br.readLine()) != null) {
sb.append(in + "\n");
}
br.close();
} catch (Exception e) {
e.printStackTrace();
}
return sb.toString();
}
Can you see what's wrong here?

Google Places API request Call

i've been struggeling with this all day now
I want to make an API call to Google Places but i can't seem to figure it out.
I've tried this: http://blog.brianbuikema.com/2010/08/android-development-part-1-using-googles-places-api-to-develop-compelling-location-based-mobile-applications/
And now I have a string like this:
http://maps.google.com/maps/api/place/search/xml?location=40.717859,-73.9577937&radius=1600&client=clientId&sensor=true_or_false&signature=SIGNATURE
Where I have the clientID as my client ID for the Places API on my gmail account and the signature filled by the UrlSinger's method signRequest
Now how do I get an XML or JSON object back?
Do I need to make a HttpRequest or a HttpPost (Or something completely different) ? I'm totally new to that.
I would love some example code.
Thanks in advance,
After another day of struggeling, I face-palmed myself.
Solution: Why would I need that signature?
A link like this works just fine:
https://maps.googleapis.com/maps/api/place/search/json?location=50.936364,5.873566&radius=500&name=ziekenhuis&sensor=false&key=FILL_IN_KEY_HERE
Retreiving the JSON object is being done by this method
private JSONObject executeHttpGet(String uri) throws Exception{
HttpGet req = new HttpGet(uri);
HttpClient client = new DefaultHttpClient();
HttpResponse resLogin = client.execute(req);
BufferedReader r = new BufferedReader(
new InputStreamReader(resLogin.getEntity()
.getContent()));
StringBuilder sb = new StringBuilder();
String s = null;
while ((s = r.readLine()) != null) {
sb.append(s);
}
Which I found here (At the bottom of the post):
http://blog.simonstahl.com/2011/03/16/login-with-oauth-to-the-foursquare-api-v2-from-android/
The method obviously needs some rewriting but it works.

How to programmatically download an HTML page in Android and get its HTML?

I need to download an HTML page programmatically and then get its HTML. I am mainly concerned with the downloading of the page. If I download the page, where will I put it?
Will I have to keep in an String variable? If yes then how?
This site provides a good explanation on how to download a file, and also how to set the location to where it should be stored. You do not have to, and should not, keep it in a string variable. If you are to manipulate the data I would suggest you use an XML parser.
You can call this method in doInBackground of AsyncTask
String html = "";
String url = "ENTER URL TO DOWNLOAD";
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(url);
HttpResponse response = client.execute(request);
InputStream in = response.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder str = new StringBuilder();
String line = null;
while((line = reader.readLine()) != null)
{
str.append(line);
}
in.close();
html = str.toString();

Gain URL from google image search in android

I am trying to be able to view the source code of a webpage after being given a URL in order to parse the text for a certain string which represents and image url.
I found this post which is pretty much what I am after trying to do but can't get it working:
Post
This is my code below.
public String fetchImage() throws ClientProtocolException, IOException {
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet("www.google.co.uk/images?q=songbird+oasis");
HttpResponse response = client.execute(request);
String html = "";
InputStream in = response.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder str = new StringBuilder();
String line = null;
while((line = reader.readLine()) != null)
{
str.append(line);
}
in.close();
html = str.toString();
return html;
}
but for some reason it just does not work. It forces me to use a try catch statement in calling the method. Once this works I think it will simple from here using regex to find the string "href="/imgres?imgurl=........jpg" to find the url of a jpg image to then be shown in an image view.
Please tell me if i'm going at this all wrong.
First, Google has a search API, which will be a better solution than the scraping you are going through, since the API will be reliable, and your solution will not be.
Second, use the BasicResponseHandler pattern for string responses, as it is much simpler.
Third, saying something "just does not work" is a pretty useless description for a support site like this one. If it crashes, as kgiannakakis pointed out, you will have an exception. Use adb logcat, DDMS, or the DDMS perspective in Eclipse to examine the stack trace and find out what the exception is. That will give you some clues for how to solve whatever problem you have.

Categories

Resources