HttpResponse and BufferedReader - java

I am trying to read the buffer (android application) and set the value to my TextView 'httpStuff'. But i dont think i am getting some response from the URI.
I don't get any runtime errors. I tried many flavour of the same logic. Nothing seems to be working.
INTERNET permission is already set in the manifest. SdkVersion="15". Any help ?
HttpClient client = new DefaultHttpClient();
URI website = new URI("http://www.mybringback.com");
HttpGet request = new HttpGet();
request.setURI(website);
HttpResponse response = client.execute(request);
HttpEntity entity = response.getEntity();
InputStream is = entity.getContent();
BufferedReader in = new BufferedReader(new InputStreamReader(is));
httpStuf.setText( in.readLine());

I think you are missing the while loop and also, when you say only in.readLine(), may be it is returning you an empty line from the response, though it is having enough data.So make sure to read the reader entirely like this and check its contents.
while ((line = rd.readLine()) != null) {
httpStuf.setText(line+"\r\n");
}
Hope this will help you.

This code worked for me
InputStream is = response.getEntity().getContent();
String strResponse = inputStreamToString(is);
private String inputStreamToString(InputStream is)
{
String line = "";
StringBuilder total = new StringBuilder();
// Wrap a BufferedReader around the InputStream
BufferedReader rd = new BufferedReader(new InputStreamReader(is), 1024 * 4);
// Read response until the end
try
{
while ((line = rd.readLine()) != null)
{
total.append(line);
}
} catch (IOException e)
{
Log.e(TAG, "error build string" + e.getMessage());
}
// Return full string
return total.toString();
}

try to get the status code of response and Then you can compare with the (HTTP status)
int responseCode=response.getStatusLine().getStatusCode()

I am using this method to simply catch the HTTP response and it works fine for me.
public String httpGetResponse(String url) {
try {
Log.i("HTTP Request", "httpGet Request for : " + url);
DefaultHttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet(url);
//get.setHeader("Connection", "keep-alive");
HttpResponse response = client.execute(get);
InputStream is = response.getEntity().getContent();
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(is));
StringBuilder str = new StringBuilder();
String line = null;
while ((line = bufferedReader.readLine()) != null) {
str.append(line + "\n");
}
return str.toString();
} catch (Exception e) {
Log.e("HTTP error", "Error in function httpGetResponse : "
+ e.getMessage());
return null;
}
}

Related

How to Decode String in Java or android?

I get Data from Json in android,date get and save in String Variable.but when use DecodeUrl its error:
Error: java.lang.IllegalArgumentException: Invalid % sequence at 40:
my code:
#SuppressLint("NewApi")
public String JsonReguest(String url) {
String json = "";
String result = "";
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
HttpClient httpclient = new DefaultHttpClient();
// Prepare a request object
HttpGet httpget = new HttpGet(url);
httpget.setHeader("Accept", "application/json");
httpget.setHeader("Content-Type", "application/json");
HttpResponse response;
try {
response = httpclient.execute(httpget);
response.setHeader("Content-Type","UTF-8");
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
result = convertStreamToString(instream);
InputStream stream = new ByteArrayInputStream(result.getBytes("UTF-8"));
result = convertStreamToString(stream);
// String encode_url=URLEncoder.encode(result,"UTF-8");
// String decode_url=URLDecoder.decode(encode_url,"UTF-8");
//result=decode_url;
//String decodedUrl = URLDecoder.decode(result, "UTF-8");
result=URLDecoder.decode(result);
}
} catch (Exception e) {
Log.e("Error", e.toString());
}
return result;
}
public static String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
simple text of json :
{"CategoryID":11,"ParentID":0,"Title":"%u062E%u0648%u062F%u0631%u0648","PicAddress":""},{"CategoryID":16,"ParentID":0,"Title":"%u0627%u0645%u0644%u0627%u0643%20","PicAddress":""}
this line crashed : result=URLDecoder.decode(result);
how to Resolve Problems.
first decode specifing your encoding
String result = URLDecoder.decode(url, "UTF-8");
and then go to http://json.org/, scroll down and choose one of the supported json parsing Java libraries
As Selvin commented %uxxxx is not a standard Url encoded string , so it's obvious to get an error
you have 2 options:
Contact the service provider to fix her url encoded strings and use URLDecoder.decode in your code
write a custom decoder for such strings
P.S. ask your questions more clear to avoid getting negative points

Unknown host exception, Apache HttpClient, Java, wunderground

I've been stuck on this particular dilemma for some time, I have scoured the site and found some help, but not to my particular issue. I'm trying to connect to a website to extract JSON data from it. The host is what i'm not sure about:
DefaultHttpClient client = new DefaultHttpClient();
HttpHost targetHost = new HttpHost("www.wunderground.com", 80);
HttpGet httpGet = new HttpGet(urllink); // urllink is "api.wunderground.com/api/my_key/conditions/forecast/hourly/alerts/q/32256.json"
httpGet.setHeader("Accept", "application/json");
httpGet.setHeader("Content-type", "application/json");
HttpResponse response = client.execute(targetHost, httpGet);
HttpEntity entity = response.getEntity();
InputStream instream = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(instream));
StringBuilder stringBuilder = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
stringBuilder.append(line + "\n");
}
} catch (Exception e) {
// print stacktrace
return null;
} finally {
try {
instream.close();
} catch (Exception e) {
// print stacktrace
return null;
}
}
return stringBuilder.toString();
The host could either be www.wunderground.com or api.wunderground.com, but when I try either of them i get Unknown host exception.
I found the error. It was that I did not have the permission in the android manifest!
The call should be similar to:
http://api.wunderground.com/api/Your_Key/conditions/q/CA/San_Francisco.json
or as stated in the API,
GET http://api.wunderground.com/api/Your_Key/features/settings/q/query.format

Source Code html doesn't download completly

I try to get HTML content, everything works find except 1 thing. It doesn't download whole code and skip the content which I want to extract(urls to images, names) and I have just blank classes 'obrazek'.
Here is the code i use to get source code:
String SourceCode(String adres) throws IllegalStateException, IOException
{
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpGet httpGet = new HttpGet(adres);
HttpResponse response = null;
try {
response = httpClient.execute(httpGet, localContext);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
BufferedReader reader = new BufferedReader(
new InputStreamReader(response.getEntity().getContent()
)
);
String result = "";
while(reader.readLine() != null)
{
result += reader.readLine();
}
reader.close();
return result;
Thank you for help:)
You skip one line each time. should be
StringBuilder result = new StringBuilder();
String line;
while((line = reader.readLine()) != null)
{
result.append(line);
}
reader.close();
return result.toString();
BTW - I used StringBuilder to avoid creation of new String object each iteration - very recommended.

How do I use HttpClient in Java to retrieve a binary file?

At the moment I can retrieve a text page as follows
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet(
"http://google.com");
try {
HttpResponse response = client.execute(get);
BufferedReader rd = new BufferedReader(new InputStreamReader(
response.getEntity().getContent()));
String line = "";
while ((line = rd.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
Suppose get is targeted at a binary file. How would I save this correctly to disk?
Just don't go via a Reader - read the data from the InputStream and write to an OutputStream.
// Using Guava (guava-libraries.googlecode.com)
InputStream data = response.getEntity().getContent();
try {
OutputStream output = new FileOutputStream(filename);
try {
ByteStreams.copy(data, output);
} finally {
Closeables.closeQuietly(output);
}
} finally {
}

HttpGet not recognizing url

So I'm using the code below from a different older post, but having trouble with one part, the line for: HttpGet request = new HttpGet(url); doesn't work. In the url spot I put something like www.stackoverflow.com, but that one part won't let the code compile. I'm basically trying to pull text writing from an html website. The complete code:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(www.stackoverflow.com);
HttpResponse response = client.execute(request);
String html = "Toronto-GTA";
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();
}
HTTPGet expects an URL or a string, so try to change your request line into:
HttpGet request = new HttpGet("http://www.stackoverflow.com/");
Use a string of the form:
[scheme:][//authority][path][?query][#fragment]
i.e. "http://www.stackoverflow.com"
Try this: HttpGet request = new HttpGet("www.stackoverflow.com");
Adding to above given answers surround your code with try and catch statements to catch the exceptions.
try{
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet("www.stackoverflow.com");
HttpResponse response = client.execute(request);
InputStream in = response.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder str = new StringBuilder();
String line, html = null;
while((line = reader.readLine()) != null)
{
str.append(line);
}
in.close();
html = str.toString();
}
catch(Exception e){
//Do something here like printing the stacktrace
}

Categories

Resources