Created
April 5, 2013 05:11
-
-
Save The-Yoda/5316791 to your computer and use it in GitHub Desktop.
Android Async http connection sample code
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class GetJSONFromUrl extends AsyncTask<String, Void, RSSFeed> { | |
InputStream is = null; | |
String result = ""; | |
String error_text=""; | |
JSONObject j = null; | |
protected void doInBackground(String... urls) { | |
// http post | |
try { | |
HttpClient httpclient = new DefaultHttpClient(); | |
HttpPost httppost = new HttpPost(urls[0]); | |
HttpResponse response = httpclient.execute(httppost); | |
HttpEntity entity = response.getEntity(); | |
HttpParams myParams = null; | |
HttpConnectionParams.setConnectionTimeout(myParams, 10000); | |
HttpConnectionParams.setSoTimeout(myParams, 10000); | |
is = entity.getContent(); | |
} catch (Exception e) { | |
Log.e("log_tag", "Error in http connection " + e.toString()); | |
} | |
} | |
protected void onPostExecute(String result) { | |
try { | |
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(); | |
result = sb.toString(); | |
//System.out.println("Result = " + result); | |
} catch (Exception e) { | |
Log.e("log_tag", "Error converting result " + e.toString()); | |
} | |
// try parse the string to a JSON object | |
try { | |
//jArray = new JSONObject(result); | |
response_status = j.getString("response_status").toString().trim(); | |
if (response_status.equals("0")) { | |
String getcustomer_id = j.getString("customer_id").toString().trim(); | |
String getPassword = j.getString("password").toString() | |
.trim(); | |
passData(getcustomer_id, getPassword); | |
} else { | |
String getcustomer_id = j.getString("response_status").toString() | |
.trim(); | |
String getPassword = j.getString("error_text").toString() | |
.trim(); | |
passData(getcustomer_id, getPassword); | |
} | |
} catch (JSONException e) { | |
Log.e("log_tag", "Error parsing data " + e.toString()); | |
} | |
super.onPostExecute(result) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment