I'm trying to connect to a webservice offered by my heating at home. Putting the request URL into Chrome results in a complete XML file.
Subsequently I tried to do the same programmatically with an Android application, which unfortunately only replies about the half of the XML file.
I already tried several attempts, amongst others a simple HttpConnection:
private void androidHttpConnect() {
HttpURLConnection urlConnection=null;
try {
URL url = new URL("http://10.0.0.140:8080/user/menu");
urlConnection = (HttpURLConnection) url.openConnection();
BufferedInputStream in = new BufferedInputStream(
urlConnection.getInputStream());
Log.i("myapp",convertStreamToString(in));
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
urlConnection.disconnect();
}
}
private String convertStreamToString(InputStream is) {
return new Scanner(is).useDelimiter("\\A").next();
}
and the Android Http Client ...
HttpClient httpclient = AndroidHttpClient.newInstance("Android");
HttpGet httpget = new HttpGet("http://10.0.0.140:8080/user/menu");
HttpResponse response;
try {
response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
if (entity != null) {
long len = entity.getContentLength();
Log.d("myapp", "content length "+len);
if (len != -1) {
try {
Log.d("myapp", EntityUtils.toString(entity));
} catch (ParseException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} else {
// Stream content out
}
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Interestingly those attempts cut the result on different positions, even though they only differ in about 5 characters. At this position there is no special character and the XML is quite short.
Anyone any idea? I also tried to run it in a ASyncTask to ensure no interrupt by the UI thread, but without success.
Thanks for your help.
Finally found the solution by myself! The problem wasn't the request but the output in the LogCat. Logging every line separately obtained the desired full response!
Related
When I run the following code, I get a "connection reset by peer" exception in most instances.
String rest = System.setProperty("http.keepAlive", "false");
String uri = WEB_LOG_IN + "?user_username=" + user_email
+ "&user_password=" + user_pass + "&user_mac=" + user_mac;
HttpClient client = new DefaultHttpClient();
HttpPost httppost = new HttpPost(uri);
HttpResponse response;
String s;
try {
response = client.execute(httppost);
s = new String(EntityUtils.toByteArray(response.getEntity()),
"UTF-8");
// read json
if (s.length() > 2)
return readlogin_info(s);
else
return false;
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return false;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return false;
}
String rest = System.setProperty("http.keepAlive", "false");
returns null which means no "http.keepAlive" property.
I tried using httpurlconnection, but that also didn't work.
I am so confused because I think the code works without issue for some ISPs.
Based on my investigation the exception caused by Mikrotik Router latency! (Maybe! Please correct me if I am wrong!)
so I put the execute section in a while until it can get the answer from server, after multiple execution I see after 2 times of trying to connect it successfully get the answer.
int count = 0;
while (s == null) {
count++;
try {
response = client.execute(httpGet);
s = new String(
EntityUtils.toByteArray(response.getEntity()),
"UTF-8");
// read json
if (s.length() > 2)
{
return readlogin_info(s);
}
else
{
return false;
}
} catch (Exception e) {
e.printStackTrace();
}
I have some code that converts my HTTPResponse Object into a JSONObject, which works fine most of the time:
public static JSONObject httpResponseToJson(HttpResponse response) {
if (response != null) {
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(),
"UTF-8"));
String json = reader.readLine();
if (json != null) {
JSONObject jsonObject = new JSONObject(json);
printStatus(jsonObject);
return jsonObject;
}
} catch (JSONException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
However, sometimes it throws a the Android NetworkOnMainThread exception. I cannot figure out why, because the response is already finished and there should not be any more network IO involved in that call. For test reasons, if I allow NetworkOnMainThread, this method works fine all the time.
Note that all the HTTPResponse is fetched with an AsyncTask and this is working fine.
I am very interested in any suggestions.
Reading the response from a HttpResponse object also involves a Network Operation. Simply process that also in the doInBackground() method and modify your AsyncTask to pass to the onPostExecute() the real result once processed.
its mean you are performing some network operation on main thread.The point here is Unless the stream is not closed, you are still performing network operation so move that part into doInBackGround() too.
I have a android application, where i extract data from the multiple urls and save then as arraylist of string. It works fine, but for fetching data from 13 urls, it takes close to 15-20 sec. Where as fetching the data from same set of urls take 3-4 sec in same app built using phonegap. Here is the code below.
#Override
protected String doInBackground(String... params) {
client = new DefaultHttpClient();
for(int i=0;i<url.size();i++)
{
get = new HttpGet(url.get(i));
try {
response = client.execute(get);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
entity = response.getEntity();
InputStream is = null;
try {
is = entity.getContent();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
BufferedReader reader = new BufferedReader(
new InputStreamReader(is));
StringBuffer buffer = new StringBuffer();
String line = null;
do {
try {
line = reader.readLine();
} catch (IOException e) {
e.printStackTrace();
}
buffer.append(line);
} while (line != null);
String str = buffer.toString();
param.add(str);
}
return null;
}
Could anyone please suggest how i can speed this execution and reduce the extraction time.
You could try starting a separate thread for each iteration from the for loop.
Smth like this :
for(int i = 0; i < url.size(); i++){
//start thread that gets data from url and adds it to the list
}
I am building a news paper app for that I need to show news paper images(epaper) in gallary view... I need to download about 100 images. for that I use asyncTask and for every download image I create new AsyncTask object and,when I am trying to download image and set into gallary I have the error in middle "VM won't let us allocation... bytes" and crash the app.
new AsyncTask<String, Void, Bitmap> () {
#Override
protected Bitmap doInBackground(String... params) {
HttpGet httpRequest;
try {
httpRequest = new HttpGet(new URL(params[0]).toURI());
HttpClient httpClient = new DefaultHttpClient();
HttpResponse response = (HttpResponse) httpClient.execute(httpRequest);
HttpEntity entity = response.getEntity();
BufferedHttpEntity bufHttpEntity = new BufferedHttpEntity(entity);
InputStream is = bufHttpEntity.getContent();
return BitmapFactory.decodeStream(is);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (URISyntaxException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}/* catch (Error e) {
e.printStackTrace();
}*/
return null;
}
#Override
protected void onPostExecute(Bitmap result) {
if(result != null) {
img.setImageBitmap(ePaperInfo.getImgJpg1());
notifyDataSetChanged();
}
}
}
show the error in logcat:
Please help me
Thanks in advance.
You should definetly not keep 100 Bitmaps on memory at the same time. You need to download only the Bitmaps needed and then call recycle() before downloading new Bitmaps.
Have a look at this exaple for the preferred way of doing what you want: ImageDownloader
Another option for image loading that I use is Prime, I use it in all of my projects and its pretty simple and efficient.
my app sends a POST request to a server and gets a response using JSON format.
Sometimes my JSON response is "null" (if the request goes in time out).
In that case I need to notify the user about the timeout (dialog or toast) and avoid the app to crash.
How do I handle correctly the JSONException and avoid the app crash?
Thank you!
Marco
to avoid the crach of your app while parsing your json , try this :
if (jsonResponse == null) {
// notify user
} else {
try {
// parse json here.
} catch (JSONException e) {
Toast.makeText(this,"Error on the response", 3000).show();
}
}
check if your json response is null. only then parse the json.
if (jsonResponse == null) {
// notify user
} else {
// parse json here.
}
get full exception :
StatusLine statusLine = response.getStatusLine();
if (statusLine.getStatusCode() == HttpStatus.SC_OK) {
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
out.close();
jsonString = out.toString();
}
}catch(ConnectException e){
// handle your exception here, maybe something like
Toast.makeText(context,"Error!",5000).show();
finish();
} catch (URISyntaxException e1) {
e1.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}