Different content with Apache's DefaultHttpClient and HttpURLConnection - java

I want to read the content of a website (http://www.google.com) in an Android app. Using the deprecated DefaultHttpClient still works fine and I always get a content length of about 15.000 characters:
DefaultHttpClient client = new DefaultHttpClient();
HttpGet g = new HttpGet(target);
HttpResponse res = client.execute(g);
InputStream is = res.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
StringBuilder builder = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
builder.append(line);
}
return Base64.encodeToString(builder.toString().getBytes(), Base64.NO_WRAP);
However, when I use a HttpURLConnection to achieve the same, I get a different content with a length of about 100.000 characters.
HttpURLConnection connection = (HttpURLConnection) new URL(target).openConnection();
InputStream is = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
StringBuilder builder = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
builder.append(line);
}
return Base64.encodeToString(builder.toString().getBytes(), Base64.NO_WRAP);
Does anybody know, why there is such a big difference. Thanks!

The problem is caused by the user agent. With the following code, the two requests behave the same:
connection.setRequestProperty("User-Agent","Apache-HttpClient");

Related

Json came null in Android Java

Error:
E/JSON Parser: Error parsing data org.json.JSONException: End of input at character 0 of
I have to send image to server with post method but I cant send. Json came to me null. There is my code:
if (method.equalsIgnoreCase("POST")) {
URL url_ = new URL(url);
String paramString = URLEncodedUtils.format(params, "utf-8"); // unused
HttpURLConnection httpConnection = (HttpURLConnection) url_.openConnection();
httpConnection.setReadTimeout(10000);
httpConnection.setConnectTimeout(15000);
httpConnection.setRequestMethod("POST");
httpConnection.setDoInput(true);
httpConnection.setDoOutput(true);
InputStream in = httpConnection.getInputStream();
OutputStream out = new FileOutputStream(picturePath);
copy(in, out);
out.flush();
out.close();
httpConnection.connect();
//Read 2
BufferedReader br = new BufferedReader(new InputStreamReader(httpConnection.getInputStream()));
String line2 = null;
StringBuilder sb = new StringBuilder();
while ((line2 = br.readLine()) != null) {
sb.append(line2);
}
br.close();
json = sb.toString();
}
How can I send image to server?
Thanks..

How do I put data I have received from a Http request into an array?

I need to insert post request data into array. I will get three sets of JSON information and I want to insert each JSON result in a String array. Here is the code I am currently using.
URL url = new URL("http://localhost:9090/service.php");
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuffer response = new StringBuffer();
int i = 0;
ArrayList<String> arr = new ArrayList<String>();
while ((line = reader.readLine()) != null) {
response.append(line);
arr.add(response.toString());
System.out.println(arr.get(i));
i++;
}
If input like:
abc
def
ghi
This code outputs like:
abc
abcdef
abcdefghi
But I need output like input.
Move
StringBuffer response = new StringBuffer();
to the first line in your 'while' block
You have not reinitialized your StringBuffer variable response. In addition, you don't really need to use StringBuffer, since you are not manipulating the string information. I suggest you try the following (and at some point you won't want to use localhost):
URL url = new URL("http://localhost:9090/service.php");
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
int i = 0;
ArrayList<String> arr = new ArrayList<String>();
while ((line = reader.readLine()) != null) {
arr.add(line);
// debug information
System.out.println(arr.get(i));
i++;
}
change arr.add(response.toString()); to arr.add(line); and it works.

bufferedreader Inputstream reader changes...?

URL u = new URL(url);
String expected = "";
HttpURLConnection uc = (HttpURLConnection) u.openConnection();
InputStream in = new BufferedInputStream(uc.getInputStream());
Reader r= new InputStreamReader(in);
so here is my code and i want a very little help that is the above is to fetch the content from url but now i want to use the same code for reading content from file what i need to change in above code....i mean there should be something which i need to change in the place of uc.getInputStream()...so what is that
InputStream in = new BufferedInputStream(uc.getInputStream());
Look at class FileInputStream.
You can simply user that code and do it in similar way.
InputStream in = new FileInputStream(new File("C:/temp/test.txt"));
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder out = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
out.append(line);
}
System.out.println(out.toString()); //Prints the string content read from input stream
reader.close();

Internet request works the first time, but not on subsequent requests

On the first request it goes to the internet and retrieves the data. When I try it again, it just gives me the data that is already in the inputstream. How do I clear the cached data, so that it does a new request each time?
This is my code:
InputStreamReader in = null;
in = new InputStreamReader(url.openStream());
response = readFully(in);
url.openStream().close();
Recreate the URL object each time.
You can create a URLConnection and explicitly set the caching policy:
final URLConnection conn = (URLConnection)url.openConnection();
conn.setUseCaches(false); // Don't use a cached copy.
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
See The Android URLConnection documentation for more details.
HttpClient API might be useful
address = "http://google.com"
String html = "";
HttpClient httpClient = DefaultHttpClient();
HttpGet httpget = new HttpGet(address);
BufferedReader in = null;
HttpResponse response = null;
response = httpClient.execute(httpget);
in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String l = "";
String nl = System.getProperty("line.seperator");
while ((l = in.readLine()) != null) {
sb.append(l + nl);
}
in.close();
html = sb.toString();
You'll need to catch some exceptions

Get web content

I'm trying to get XML content from an URL:
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet();
request.setURI(new URI("http://www.domain.com/test.aspx"));
HttpResponse response = client.execute(request);
in = response.getEntity().getContent();
When I write out the response content, this is truncated before the end of the content.
Any idea?
Did you use a InputStreamReader for the input stream in?
String s = "";
String line = "";
BufferedReader rd = new BufferedReader(new InputStreamReader(in));
try {
while ((line = rd.readLine()) != null) { s += line; }
} catch (IOException e) {
// Handle error
}
// s should be the complete string
maybe i have solved, was the android emulator. Simply restarting it all works fine.
Thanks to all

Categories

Resources