问题
First of all I have two things that need your attention:
1) I tried this code on phones with api level lower than 11 and phones that are pretty high, like 4.3 or 4.4. The high api leveled phones were unable to make this code work unlike the other ones. 2)I have almost the exact code in another page, using it, it's working on all apis, only the one I'm going to show you isn't working. Thank you for listening.
This is my method that makes the connection:
public static StringBuilder httpGetConnection (String urlStr, Context dialogCtx) {
final String noServ = "Server Error";
final String noServErr = "Server is unavailable";
StringBuilder err= new StringBuilder();
err.append("Error!");
HttpURLConnection conn = null;
BufferedReader rd = null;
StringBuilder sb = null;
try {
URL url = new URL(urlStr);
conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(6000);
conn.setReadTimeout(10000);
if (conn.getResponseCode() >= 200 && conn.getResponseCode() <= 299) {
// Buffer the result into a string
rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
sb = new StringBuilder();
String line;
while ((line = rd.readLine()) != null) {
sb.append(line);
} //string builder dolduruldu
rd.close();
conn.disconnect();
}
else {
AlertDialogDisp(dialogCtx, noServ, noServHata);
}
}
catch (Exception e) {
return err;
}
finally {
if (rd != null) {
try {
rd.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (conn != null) {
conn.disconnect();
}
}
return sb;
}
And this is my code that 'uses' the method:
try {
JSONTokener neuTokener = new JSONTokener(Sources.httpGetConnection (UrlStr, getActivity()).toString());
JSONArray neuArray=new JSONArray(neuTokener);
for(int i=0; i<(neuArray.length()); i++)
{
JSONObject json_obj_neu_sip = neuArray.getJSONObject(i);
wartSip = json_obj_neu_sip.getString("mit");
wartSip2 = json_obj_neu_sip.getString("tua");
akkSip = json_obj_neu_sip.getString("ptar");
ajjSip = json_obj_neu_sip.getString("ptar2");
}
...
I'm using this code, which uses the method, in a fragment. When I try to launch it, the neuTokener
's value is "Error!". The StringBuilder
from my method when it falls to catch. But I have no idea why it catches the thing, I use this in different places and there is no problem.
I'd really appreciate the help, thanks in advance.
回答1:
You need to implement all the Network Calls
in background Thread via AsyncTask
.
Here is a dummy template, you can modify it according to your needs:
private class LongOperation extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... params) {
//Send your HTTP REQUESTS HERE.
return "";
}
@Override
protected void onPostExecute(String result) {
//UPDATE YOUR UI HERE AFTER RETRIEVING DATA FROM HTTP REQUEST
}
@Override
protected void onPreExecute() {}
@Override
protected void onProgressUpdate(Void... values) {}
}
}
You need to call this AsyncTask, like this: new LongOperation().execute();
I hope this helps.
回答2:
A very common mistake - is a trying call a httpGetURLConnection in main UI thread, cause it is a very heavy operation and UI mustn't "get frozen" while you've work with httpGetURLConnection , so that why in new android versions(after honeyComb) its totaly deprecated. You should use an asyncTask for working with httpGetURLConnection.
回答3:
Probably you are getting NetworkOnMainThreadException connection error.
So best way is to use AsyncTask for that.
For more details go with this
来源:https://stackoverflow.com/questions/20567613/httpurlconnection-working-on-api-level-11-not-working-on-api-level-11-on-and