I am calling a url to fetch data and insert in my database. I have provided a no internet check. If I open the app without internet connection, it works fins, a pop up comes.. But if I connect to the url when I have internet and the internet goes in middle the process, my app crashes, How to fix it?
My code:
public class DoPOSTPen extends AsyncTask<String, Void, Boolean> implements OnCancelListener {
#SuppressWarnings("deprecation")
#Override
protected Boolean doInBackground(String... arg0) {
try {
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet("http://testapi.pharmeazy.in/api/MediEazy/GetAllInvoices");
request.addHeader("Authorization", " basic NDlyaWNva2pvaWQwM2ptZGlraWRES09qZGZpamRmNzY0dDA4NWp6MzcyOHdzMkpJS1M4MTA0c2NvcTJ1OTRkazphd0VEMzI3MkA4WWFzZEU3MjI3IUBeIypVSFMq");
request.setHeader(HTTP.CONTENT_TYPE, "application/json");
System.out.println("PRIINTING");
HttpResponse response = null;
try {
response = client.execute(request);
Log.d("Response of GET request", response.toString());
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
InputStream inputStream = response.getEntity().getContent();
String result = Utils.convertInputStreamToString(inputStream);
System.out.println("server response is :" + result + "\n" + inputStream);
try {
ja=new JSONArray(result);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
catch (Exception e) {
Log.e("ClientServerDemo", "Error:", e);
toastText2 = "Connection Error !";
}
return true;
}
protected void onPreExecute() {
//display the progress dialog
mProgressHUD2 = ProgressHUD.show(Med.this,"Getting Rejected Orders", true,false,this);
}
#Override
protected void onPostExecute(Boolean valid) {
mProgressHUD2.dismiss();
// if server response is successful
for(int i=0;i<ja.length();i++){
try {
jo=ja.getJSONObject(i);
db.insertLabel(jo.get("Id").toString(), jo.get("CustomerId").toString(), jo.get("PharmacyId").toString(),
jo.get("DeliveryAddress").toString(), jo.get("DeliveryName").toString(),
jo.get("OrderStatus").toString(),jo.get("PrescriptionAttached").toString(),jo.get("Discount").toString());
}
catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
new DoPOST3().execute();
}
Please help
why you don't go for httpurlconection
#Override
protected String doInBackground(String... params) {
String finalResult = null;
URL url = null;
HttpsURLConnection urlConnection = null;
try {
url=new URL(URL);
urlConnection = (HttpsURLConnection) url.openConnection();
urlConnection.setDoOutput(true);
urlConnection.setDoInput(true);
urlConnection.setRequestMethod("POST");
urlConnection.setUseCaches(false);
urlConnection.setConnectTimeout(5000);
urlConnection.setReadTimeout(5000);
urlConnection.setRequestProperty("Content-Type","application/json");
urlConnection.connect();
OutputStreamWriter out = new OutputStreamWriter(urlConnection.getOutputStream());
out.write(jsonObjSend.toString());
out.close();
starttime = System.currentTimeMillis();
try {
mResponseCode = urlConnection.getResponseCode();
totaltime = System.currentTimeMillis() - starttime;
Log.e("HTTP POST Response Code:", ""
+ mResponseCode);
} catch (SSLPeerUnverifiedException e) {
Log.e("Exception", Log.getStackTraceString(e));
} catch (IOException e) {
Log.e("Exception", Log.getStackTraceString(e));
Log.e("HTTP POST Response Code(2):", ""
+ mResponseCode);
}
}
check before calling asynctask
if(Util.haveNetworkConnection(this))
{
HttpPostData req=new HttpPostData(URL, createJsonObject(),this) ;
req.execute();
}
Related
I have a HTTP handler class that will handle the calls to a ASYNC method. Everything works fine, I am able to gather information from the json and display it inside of the application, however, I have noticed that I sometimes get the following in my log.
A connection to http://www.abc123.com/ was leaked. Did you forget to close a response body?
Is there any specific reason why I would be getting this. I am closing in within the try method in convertStreamToString.
public class HttpHandler {
private static final String TAG = HttpHandler.class.getSimpleName();
public HttpHandler() {
}
public String makeServiceCall(String reqUrl) {
String response = null;
try {
URL url = new URL(reqUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
// read the response
InputStream in = new BufferedInputStream(conn.getInputStream());
response = convertStreamToString(in);
} catch (MalformedURLException e) {
Log.e(TAG, "MalformedURLException: " + e.getMessage());
} catch (ProtocolException e) {
Log.e(TAG, "ProtocolException: " + e.getMessage());
} catch (IOException e) {
Log.e(TAG, "IOException: " + e.getMessage());
} catch (Exception e) {
Log.e(TAG, "Exception: " + e.getMessage());
}
return response;
}
private String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line;
try {
while ((line = reader.readLine()) != null) {
sb.append(line).append('\n');
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
}
I am trying to save every output data in asynctask for each http call.But I am unable to see any data in a file.I really appreciate any help.Thanks in Advance.
final String[] ar={"1","2","3",.............,"25"}
filename="test_file";
myFile = new File("/sdcard/"+filename);
try {
myFile.createNewFile();
fOut = new FileOutputStream(myFile);
} catch (FileNotFoundException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
myOutWriter = new OutputStreamWriter(fOut);
for ( j = 0; j < ar.length; j++) {
u="http://www.example.com/"+ar[j];
JSONParser jParser=new JSONParser();
new MyAsyncTask().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,u);
}
try {
myOutWriter.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
class MyAsyncTask extends AsyncTask<String, String, Void> {
private ProgressDialog progressDialog = new ProgressDialog(MainActivity.this);
InputStream inputStream = null;
String result = "";
protected void onPreExecute() {
progressDialog.setMessage("Downloading your data...");
progressDialog.show();
progressDialog.setOnCancelListener(new OnCancelListener() {
public void onCancel(DialogInterface arg0) {
MyAsyncTask.this.cancel(true);
}
});
}
#Override
protected Void doInBackground(String... params) {
String url_select = params[0];
try {
HttpClient httpclient = new DefaultHttpClient();
HttpResponse httpResponse = httpclient.execute(new HttpGet(url_select));
// receive response as inputStream
inputStream = httpResponse.getEntity().getContent();
//
// // Read content & Log
// inputStream = httpEntity.getContent();
} catch (UnsupportedEncodingException e1) {
Log.e("UnsupportedEncodingException", e1.toString());
e1.printStackTrace();
} catch (ClientProtocolException e2) {
Log.e("ClientProtocolException", e2.toString());
e2.printStackTrace();
} catch (IllegalStateException e3) {
Log.e("IllegalStateException", e3.toString());
e3.printStackTrace();
} catch (IOException e4) {
Log.e("IOException", e4.toString());
e4.printStackTrace();
}
// Convert response to string using String Builder
try {
BufferedReader bReader = new BufferedReader(new InputStreamReader(inputStream, "iso-8859-1"), 8);
StringBuilder sBuilder = new StringBuilder();
String line = null;
while ((line = bReader.readLine()) != null) {
sBuilder.append(line + "\n");
}
inputStream.close();
result = sBuilder.toString();
} catch (Exception e) {
Log.e("StringBuilding & BufferedReader", "Error converting result " + e.toString());
}
return null;
} // protected Void doInBackground(String... params)
protected void onPostExecute(Void v) {
//parse JSON data
try{
JSONObject jArray = new JSONObject(result);
String name = jArray.getString("name");
if (name!=null) {
Log.w("idname", name);
//
myOutWriter.append(name).append("\r\n");
//
Toast.makeText(getBaseContext(), name, 5).show();
}
// End Loop
this.progressDialog.dismiss();
} catch (JSONException e) {
Log.e("JSONException", "Error: " + e.toString());
} // catch (JSONException e)
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} // protected void onPostExecute(Void v)
} //class MyAsyncTask extends AsyncTask<String, String, Void>
for ( j = 0; j < ar.length; j++) {
u="http://www.example.com/"+ar[j];
JSONParser jParser=new JSONParser();
new MyAsyncTask().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,u);
}
try {
myOutWriter.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
You close the myOutWriter after start MyAsyncTask. So when MyAsyncTask try to write data to file, it throw OutputStreamWriter is closed exception.
You need remove the code of close myOutWriter from here. Add add close code at the end of onPostExecute like below:
void onPostExecute(Void v) {
.....
} catch (JSONException e) {
Log.e("JSONException", "Error: " + e.toString());
} // catch (JSONException e)
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
int count = taskCount.decrementAndGet()
if(count == 0 ) {
try {
myOutWriter.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} // protected void onPostExecute(Void v)
the definition of taskCount is like this:
AtomicInteger taskCount = new AtomicInteger(ar.length - 1);
At last, I think Thread and CountDownLatch is better option
check if entity not null then write to db
HttpEntity entity = response.getEntity();
if(entity!=null ){
inputStream = entity.getContent();
}
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
url3="http://www.digitalmarketingbox.com/webtool/boxdata/"+MainActivity.abc+"/updates.zip";
try {
HttpURLConnection.setFollowRedirects(false);
// note : you may also need
// HttpURLConnection.setInstanceFollowRedirects(false)
HttpURLConnection con =(HttpURLConnection) new URL(params[0]).openConnection();
con.setRequestMethod("HEAD");
x=con.getResponseCode() == HttpURLConnection.HTTP_OK;
}
catch (Exception e) {
e.printStackTrace();
x=false;
}
try {
HttpURLConnection.setFollowRedirects(false);
// note : you may also need
// HttpURLConnection.setInstanceFollowRedirects(false)
HttpURLConnection con =(HttpURLConnection) new URL(url3).openConnection();
con.setRequestMethod("HEAD");
xc=con.getResponseCode() == HttpURLConnection.HTTP_OK;
}
catch (Exception e) {
e.printStackTrace();
xc=false;
}
//x=exists(params[0]);
//xc=exists(url3);
valve=String.valueOf(x);
if(valve.equals("true"))
{
finalurl=url+ MainActivity.abc + "/resources.zip";
filename="resources.zip";
MainActivity.fl1=filename;
Log.i("filename",filename);
}
else if(xc==true)
{
finalurl=url+ MainActivity.abc + "/updates.zip";
filename="updates.zip";
MainActivity.fl1=filename;
Log.i("filename",filename);
}
else
{
try
{
HttpClient client = new DefaultHttpClient();
Log.i("url for checking update",url1);
HttpPost post = new HttpPost(url1);
List<NameValuePair> parameters = new ArrayList<NameValuePair>();
parameters.add(new BasicNameValuePair("reqtype", "resendcontent"));
parameters.add(new BasicNameValuePair("menuboxid",MainActivity.abc));
parameters.add(new BasicNameValuePair("updatetoken", "dmb20101512"));
UrlEncodedFormEntity ent;
ent = new UrlEncodedFormEntity(parameters,HTTP.UTF_8);
post.setEntity(ent);
HttpResponse responsePOST = client.execute(post);
HttpEntity resEntity = responsePOST.getEntity();
finalurl=url+ MainActivity.abc + "/updates.zip";
filename="updates.zip";
MainActivity.fl1=filename;
Log.i("filename",filename);
Log.i("url",finalurl);
}
catch (final IOException e) {
e.printStackTrace();
}
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finalurl=url+ MainActivity.abc + "/updates.zip";
filename="updates.zip";
MainActivity.fl1=filename;
}
try{
URL url = new URL(finalurl);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
urlConnection.connect();
//File SDCardRoot = Environment.getExternalStorageDirectory();
filedestination=Environment.getExternalStorageDirectory() +"/" + filename;
//File file = new File(SDCardRoot,filename);
File file = new File(filedestination);
FileOutputStream fileOutput = new FileOutputStream(file);
InputStream inputStream = urlConnection.getInputStream();
totalSize = urlConnection.getContentLength();
Log.i("size",String.valueOf(totalSize));
byte[] buffer = new byte[1024];
int bufferLength = 0;
while ( (bufferLength = inputStream.read(buffer)) > 0 ) {
fileOutput.write(buffer, 0, bufferLength);
downloadedSize += bufferLength;
}
//close the output stream when complete //
fileOutput.close();
}
catch (final IOException e) {
e.printStackTrace();
}
Log.i("download info","Download complete");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String source = Environment.getExternalStorageDirectory() + "/" + filename;
Log.i("Download destination",source);
String destination =Environment.getExternalStorageDirectory()+ "/";
Log.i("Extract destination",destination);
try {
ZipFile zipFile = new ZipFile(source);
zipFile.extractAll(destination);
} catch (ZipException e) {
e.printStackTrace();
}
try
{
HttpClient client1 = new DefaultHttpClient();
Log.i("url is",url1);
HttpPost post1 = new HttpPost(url1);
List<NameValuePair> parameters1 = new ArrayList<NameValuePair>();
parameters1.add(new BasicNameValuePair("reqtype", "completeupdate"));
parameters1.add(new BasicNameValuePair("menuboxid",MainActivity.abc));
parameters1.add(new BasicNameValuePair("updatetoken", "dmb20101512"));
UrlEncodedFormEntity ent1 = new UrlEncodedFormEntity(parameters1,HTTP.UTF_8);
post1.setEntity(ent1);
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return foo;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stu
super.onPostExecute(result);
//result=bn;
/*if(!result.isEmpty())
{
Calendar c = Calendar.getInstance();
int seconds = c.get(Calendar.SECOND);
Log.i("AsyncTask finish time",String.valueOf(seconds));
}*/
}
i am using this asynctask class in my activity to do some task and checking via the getstatus method that it has finished or not ,but it is never finished
above is my code of my asynctask class and its postexecute is not working can someone expalin me why?
I have also experienced the same problem. It happens when your Main UI thread goes to sleep. Try to use a timer in your UI thread to keep it awake.
Sir,,
I would like to try my application to test push-notification by typing this link below , but it comes to trying , there is no effect.Would you please tell me what is the correct format for the hyperlink to test my Application program ?
The below is my link
https://android.googleapis.com/gcm/send?registration_ids=
APA91bHhJQJGK1OJxYHcZeH81JoAprU97CAvMHQ58cHj3MYHD204MTn1W9Kl_i51UV8ej5qwLfkwvK-vihfuWjXG6iBvkUZJuclqoNbAjx_K2mN_P2ai4rI82P0dax_tm7NHc-k_1FsBn6hvwxjxxPdgMdtYpSIdwA
&data.message="hello testing"
collapse_key=score_update&time_to_live=108&delay_while_idle=1&data.message=" + value + "
You can actually test it from the Android device itself:
public class PushTester {
final static private String deviceId = "YOUR_DEVICE_ID";
final static private String apiId = "YOUR_API_ID";
final static private String sendUrl = "https://android.googleapis.com/gcm/send";
static void testPush() {
URL url;
HttpsURLConnection urlConnection;
OutputStream os = null;
InputStream is = null;;
try {
url = new URL(sendUrl);
urlConnection = (HttpsURLConnection) url.openConnection();
urlConnection.setUseCaches(false);
urlConnection.setConnectTimeout(3000);
urlConnection.setReadTimeout(3000);
urlConnection.setRequestMethod("POST");
urlConnection.setRequestProperty("User-Agent", "Android Push tester");
urlConnection.setRequestProperty("Content-Type", "application/json");
urlConnection.setRequestProperty("Authorization", "key="+apiId);
JSONObject message = new JSONObject();
JSONArray regIds = new JSONArray();
JSONObject data = new JSONObject();
regIds.put(deviceId);
message.put("registration_ids", regIds);
//message.put("collapse_key", value)
data.put("something", "value");
message.put("data", data);
urlConnection.setDoOutput(true);
os = urlConnection.getOutputStream();
os.write(message.toString().getBytes());
os.flush();
int status = urlConnection.getResponseCode();
is = urlConnection.getInputStream();
byte[] response = new byte[4096];
is.read(response);
String responseText = String.valueOf(response);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally {
try {
if (os != null) {
os.close();
}
if (is != null) {
is.close();
}
}
catch (Exception ex) {
ex.printStackTrace();
}
os = null;
is = null;
}
}
}
Hello here I am trying for the post data from android to server.I am trying using HttpURLConnection.
Here I am sending username & password for Authentication for entering data for particular user in drupal. I have also tried to post data with various other methods. Using DefaultHttpClient but no luck. I am getting 401 error with using DefaultHttpClient.
Here is the link of question that I have asked on stackoverflow. Authentication error: Unable to respond to any of these challenges: {} Android - 401 Unauthorized
SO please help. Thanks for listening.
Here is my code.
public static class post_idea extends AsyncTask<Void, Void, Void> {
String strResponse1;
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
pgb.setVisibility(View.VISIBLE);
}
#Override
public Void doInBackground(Void... params) {
// TODO Auto-generated method stub
// String url = "http://testingd7.mobileapplicationtesters.com/my_android_drupal/user/login";
String url = "http://testingd7.mobileapplicationtesters.com/my_android_drupal/node.json";
// String url = "http://mobiappdevelopers.com/drupal_test/my_android_drupal/node.json";
//String url = "http://www.drupal7.mobileapplicationtesters.com/my_services/node.json";
strResponse1 = makeWebForPostIdea(url,title,body);
System.out.println("=========> Response from post idea => "
+ strResponse1);
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
pgb.setVisibility(View.GONE);
}
public static String makeWebForPostIdea(String url123, String title,String body)
{
HttpURLConnection httpcon = null;
JSONObject json = null;
JSONObject jsonnode = null;
try {
JSONObject jsonvalue = new JSONObject();
jsonvalue.put("value", body.toString());
JSONArray array = new JSONArray();
array.put(jsonvalue);
jsonnode = new JSONObject();
jsonnode.put("und", array);
System.out.println("######2 jsonnode=======>"+jsonnode.toString());
json = new JSONObject();
json.put("title",title);
json.put("body", jsonnode);
json.put("type","article");
System.out.println("value of the combine node=======>"+json.toString());
} catch (JSONException e3) {
// TODO Auto-generated catch block
e3.printStackTrace();
}
try {
httpcon = (HttpURLConnection) ((new URL(url123).openConnection()));
httpcon.setDoOutput(true);
httpcon.setRequestProperty("Content-Type", "application/json");
httpcon.setRequestProperty("Accept", "application/json");
httpcon.setRequestMethod("POST");
String urlParameters =
"type=" + URLEncoder.encode("page", "UTF-8") +
"title=" + URLEncoder.encode(title, "UTF-8") +
"body" + URLEncoder.encode(jsonnode.toString(), "UTF-8") ;
httpcon.setRequestProperty("Content-Length", "" +
Integer.toString(urlParameters.getBytes().length));
} catch (ProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
httpcon.connect();
byte[] outputBytes = "{\"username\":\"uname\",\"password\":\"pass\"}".getBytes("UTF-8");
OutputStream os = httpcon.getOutputStream();
os.write(outputBytes);
os.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
Thanks.
You set the content length here:
httpcon.setRequestProperty("Content-Length", "" + Integer.toString(urlParameters.getBytes().length));
But the content you sent comes from here:
byte[] outputBytes = "{\"username\":\"uname\",\"password\":\"pass\"}".getBytes("UTF-8");
OutputStream os = httpcon.getOutputStream();
os.write(outputBytes);
So the reported Content-Length does not match the actual content length.
Ignore the httpcon.connect(); in the middle, it does nothing because you are already connected.
Instead, you need to do:
byte[] outputBytes = "{\"username\":\"uname\",\"password\":\"pass\"}".getBytes("UTF-8");
httpcon.setRequestProperty("Content-Length", Integer.toString(outputBytes.length()));
OutputStream os = httpcon.getOutputStream();
os.write(outputBytes);