NetworkOnMainThreadException android activity [duplicate] - android

This question already has answers here:
How can I fix 'android.os.NetworkOnMainThreadException'?
(66 answers)
Closed 6 years ago.
I am using this code to retrieve website data inside android activity.It is throwing android.os.networkonmainthreadexception
try
{
URL url = new URL("https://enigmatic-woodland-35608.herokuapp.com/pager.json");
URLConnection tc = url.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(
tc.getInputStream()));
String line, newl = " ";
while ((line = in.readLine()) != null) {
newl += line.trim();
}
System.out.println("newl" + newl.trim());
} catch (Exception e) {
Log.e("exception", e.toString());
}
Please give me a possible solution..

Network oprations/call cannot be done in main thread. You need to run it from another thread , asynchronous task or an intent service
Note : All UI opration shoud be done onPostExecute,onPreExecute
The below code may help you to solve.
Call AsyncTask where you want
new PagerAsyncTask().execute();
class PagerAsyncTask extends AsyncTask<String,Void,String>{
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
StringBuilder sb=null;
BufferedReader reader=null;
String serverResponse=null;
try {
URL url = new URL(""https://enigmatic-woodland-35608.herokuapp.com/pager.json"");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setConnectTimeout(5000);
connection.setRequestMethod("GET");
connection.connect();
int statusCode = connection.getResponseCode();
//Log.e("statusCode", "" + statusCode);
if (statusCode == 200) {
sb = new StringBuilder();
reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
}
connection.disconnect();
if (sb!=null)
serverResponse=sb.toString();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
return serverResponse;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
//All your UI operation can be performed here
//Response string can be converted to JSONObject/JSONArray like
JSONObject response=new JSONObject(s);
System.out.println(s);
}
}

Network operations can involve unpredictable delays. To prevent this
from causing a poor user experience, always perform network operations
on a separate thread from the UI.
Please check the doc.

I am using a NetworkOps util in my projects. Try it:
import android.content.Context;
import android.net.Uri;
import android.util.Log;
import com.csehelper.variables.Constants;
import com.csehelper.variables.Keys;
import com.csehelper.variables.Url;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.ProtocolException;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.util.ArrayList;
public class NetworkOps {
public final String EXCEPTION = "~Exception~";
/****************************
* Method to Grab Source
****************************/
public static String GrabSource(String URL) {
return PostData(URL, null);
}
/**
* *****************************************
* Method to Grab Source code from URL
* Posting Data
* *****************************************
*/
private static String PostData(String url, Uri.Builder uribuilder) {
String Source;
HttpURLConnection.setFollowRedirects(false);
HttpURLConnection urlConnection = null;
try {
urlConnection = (HttpURLConnection) new URL(url).openConnection();
urlConnection.setDoOutput(true);
urlConnection.setConnectTimeout(10000);
if(uribuilder != null) {
String query = uribuilder.build().getEncodedQuery();
OutputStream os = urlConnection.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(query);
writer.flush();
writer.close();
os.close();
}
urlConnection.connect();
if (urlConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
String line;
StringBuilder builder = new StringBuilder();
InputStreamReader isr = new InputStreamReader(
urlConnection.getInputStream());
BufferedReader reader = new BufferedReader(isr);
while ((line = reader.readLine()) != null) {
builder.append(line);
}
Source = builder.toString();
} else {
Source = EXCEPTION + "Server unreachable. Check network connection.";
}
} catch (SocketTimeoutException e) {
Source = EXCEPTION + "Connection timed out.";
} catch (java.net.UnknownHostException e) {
Source = EXCEPTION + Constants.EXCEPTION_NO_NET;
} catch (ArrayIndexOutOfBoundsException e) {
Source = EXCEPTION + "Server error";
} catch (ProtocolException e) {
Source = EXCEPTION + "Protocol error";
} catch (IOException e) {
Source = EXCEPTION + "Server unreachable. Check network connection.";
} catch (Exception e) {
Source = EXCEPTION + "Error:" + e.toString() + " - "
+ e.getMessage();
e.printStackTrace();
} finally {
if (urlConnection != null) urlConnection.disconnect();
}
return Source;
}
}
Call these Static Functions from AsyncTask:
/*********************************
* AsyncTask to GrabSource
********************************/
class AsyncTask_GrabSource extends AsyncTask<Void, Void, Void> {
String Source = null;
String url = "https://enigmatic-woodland-35608.herokuapp.com/pager.json";
#Override
protected void onPreExecute() {
//Runs on Main Thread. You can access your UI elements here.
}
#Override
protected Void doInBackground(Void... params) {
// Don't access any UI elements from this function
Source = NetworkOps.GrabSource(this.url);
return null;
}
#Override
protected void onPostExecute(Void result) {
if (Source != null) {
if (!Source.contains(EXCEPTION)) {
//Show Error Message or do whatever you want
} else {
//Do Whatever with your Grabbed Sourcecode.
// This function runs on UI Thread, so you can update UI elements here
}
}
}
You can also post data with the function PostData. In method doInBackground, add this:
Uri.Builder builder = new Uri.Builder()
.appendQueryParameter("key", "value")
.appendQueryParameter("key2", "value2");
Source = NetworkOps.PostData(getApplicationContext(), url, builder);

Related

Sending Variables to a REST api to be saved on server

I am really struggling with this for some time now and I am really lost in terms of how this works.
I have written a REST service in netbeans and I have passed through Json data and tested that it works using Postman and it is successfully saving to the database.
Now, I want the variables in my mobile application to be sent to that REST api so that they can then be saved to the database.
I have looked at many answers on this but can get none which fully explain to me how to do this.. Ideally I am trying to POST or PUT data from my mobile app into my database.
Here is what I have tried so far:
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
details = editTextDetails.getText().toString();
getCurrentDateandTime();
String url = "http://localhost:8080/engAppApi/webservices/engineerTable/";
HttpClient client = new DefaultHttpClient();
HttpPost request = new HttpPost(url);
JSONObject params = new JSONObject();
try {
params.put("machinetype", machineType);
} catch (JSONException e) {
e.printStackTrace();
}
try {
params.put("workordernumber", workOrderNumber);
} catch (JSONException e) {
e.printStackTrace();
}
try {
params.put("employeename", employee);
} catch (JSONException e) {
e.printStackTrace();
}
try {
params.put("activity", activity);
} catch (JSONException e) {
e.printStackTrace();
}
try {
params.put("durationhours", durationHours);
} catch (JSONException e) {
e.printStackTrace();
}
try {
params.put("durationmins", durationMins);
} catch (JSONException e) {
e.printStackTrace();
}
try {
params.put("downtimehours", downTimeHours);
} catch (JSONException e) {
e.printStackTrace();
}
try {
params.put("downtimemins", downTimeMins);
} catch (JSONException e) {
e.printStackTrace();
}
try {
params.put("details", details);
} catch (JSONException e) {
e.printStackTrace();
}
try {
params.put("currentdateandtime", currentDateandTime);
} catch (JSONException e) {
e.printStackTrace();
}
StringEntity jsonEntity = null;
try {
jsonEntity = new StringEntity(params.toString());
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
request = new HttpPost(url);
request.addHeader("Content-Type", "application/json");
request.setEntity(jsonEntity);
try {
HttpResponse response = client.execute(request);
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
can someone please point me in the right direction
Thanks in advance!
just use retrofit 2 for connect to server.
see this link
You have an idea in how to do the post petition, but you have a couple of problems. The first and more important problem is that if you want to retrieve information from a server, you must put your code in an async task. You can't do it in UI Thread. So, i'm gonna share with you a class that implements all the logic you need and you just have to use it. First you need to use gson, look how to use it here
https://github.com/google/gson
and the code is here. It have two methods, one for GET and other for POST.
import android.os.AsyncTask;
import android.util.Log;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
/**
* Created by Administrador on 4/27/2017.
*/
public class JsonReaderFromUrl {
public static final int SUCCESS = 0;
public static final int FAILED = 1;
public static final int PROGRESS = 2;
public interface OnJesonInterface{
void OnJsonReceive(int status, JSONObject jsonObject, int key);
}
public JsonReaderFromUrl() {
}
public void getJsonFromUrlPost(final String url, final OnJesonInterface onJesonInterface, final String body, final int key){
new AsyncTask<Void, String, String>() {
#Override
protected void onPreExecute() {
super.onPreExecute();
onJesonInterface.OnJsonReceive(PROGRESS,null,0);
}
#Override
protected String doInBackground(Void... params) {
if(android.os.Debug.isDebuggerConnected())
android.os.Debug.waitForDebugger();
try {
URL urlJson = new URL(url);
HttpURLConnection connection = (HttpURLConnection) urlJson.openConnection();
connection.setDoInput(true);
connection.setRequestProperty("Content-Type","application/json");
connection.setRequestMethod("POST");
OutputStream outputStream = connection.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
writer.write(body);
writer.flush();
writer.close();
outputStream.close();
connection.connect();
StringBuilder stringBuilder = new StringBuilder();
int httpStatus = connection.getResponseCode();
if (httpStatus == HttpURLConnection.HTTP_CREATED){
BufferedReader br = new BufferedReader(
new InputStreamReader(connection.getInputStream(),"utf-8")
);
String line = "";
while ((line = br.readLine()) != null){
stringBuilder.append(line + "\n");
}
br.close();
return stringBuilder.toString();
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
if (s != null){
try {
JSONObject jsonObject = new JSONObject(s);
onJesonInterface.OnJsonReceive(SUCCESS,jsonObject,key);
} catch (JSONException e) {
e.printStackTrace();
}
}
else {
onJesonInterface.OnJsonReceive(FAILED,null,0);
}
}
}.execute();
}
public void getJsonFromUrl(final String url, final OnJesonInterface onJesonInterface){
AsyncTask<Void,String,String> asyncTask = new AsyncTask<Void, String, String>() {
#Override
protected void onPreExecute() {
super.onPreExecute();
onJesonInterface.OnJsonReceive(PROGRESS,null,0);
}
#Override
protected String doInBackground(Void... params) {
try {
URL urlJson = new URL(url);
HttpURLConnection connection = (HttpURLConnection) urlJson.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer stringBuffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null){
stringBuffer.append(line + "\n");
Log.d("RESPONDE JSON: ",">" + line);
}
return stringBuffer.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
if (s != null){
try {
JSONObject jsonObject = new JSONObject(s);
onJesonInterface.OnJsonReceive(SUCCESS,jsonObject,0);
} catch (JSONException e) {
e.printStackTrace();
}
}
else {
onJesonInterface.OnJsonReceive(FAILED,null,0);
}
}
}.execute();
}
}
import this class where you need and use it PD: The key value is an int that can be used to retrieve what response correspond to each petition, this in case you use this class with a lot of petitions.

android 4.3 - BufferedReader shows Please Wait message

I have the following function to allow my android app to communicate with a web server. However the app shows a 'Please Wait' message when I call this code and only disappears if a new activity loads in or if I press the back button. Where is the Please wait coming from and how can I avoid it appearing? Thanks
package util.sapa.sapacontainermanager5;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
public class SimpleWebCalls {
public String executeHttpGet(String serverIP, String nvp) {
String lines="";
serverIP="???????????";
URL url = null;
try {
url = new URL("http://" + serverIP + "/WCF.aspx?" + nvp);
HttpURLConnection conn = null;
try {
conn = (HttpURLConnection) url.openConnection();
try {
conn.setRequestMethod("GET");
BufferedReader in = null;
try {
in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuffer sb = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null) {
sb.append(line + NL);
lines+=line;
}
in.close();
return lines;
} catch (IOException e) {
e.printStackTrace();
}
} catch (ProtocolException e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
} catch (MalformedURLException e) {
e.printStackTrace();
}
return "";
}
}
the above class is called from:
public String GetDataFromServer(String serverIP,String nvp) {
SimpleWebCalls tWebCall = new SimpleWebCalls();
String sReturn="";
sReturn= tWebCall.executeHttpGet(serverIP,nvp);
return sReturn;
}
the above function is called from:
String data="";
data="doAction=location&u=" + sess.getUserName()+
"&p=" + sess.getPwd() +
"&uid=" + sess.getUserID() +
"&lf=" + sess.encodeStr(editScannedCode.getText().toString());
result = sess.GetDataFromServer(serverIP,data);
follow this tutorial link it might be helpful to you.
add GetDataFromServer() method in to your doInBackground() method.

How to resolve android.os.networkonmainthreadexception

I am new to android and I am trying to read data from a server. I use a util and call that util like this
private void ParseSource(String Url){
String source = new Cls_SourceGrabber().grabSource(Url);
}
But I am getting a android.os.networkonmainthreadexception. How can I reduce that?
My SourceGrabber util:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.URISyntaxException;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
public class Cls_SourceGrabber {
private HttpGet mRequest;
private HttpClient mClient;
private BufferedReader mReader;
private StringBuffer mBuffer;
private String mNewLine;
public Cls_SourceGrabber() {
mRequest = new HttpGet();
InitializeClient();
mReader = null;
mBuffer = new StringBuffer(10000);
mNewLine = System.getProperty("line.separator");
}
private void InitializeClient() {
if (mClient == null || mClient.getConnectionManager() == null) {
HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, 4500);
HttpConnectionParams.setSoTimeout(httpParameters, 10000);
// HttpConnectionParams.setTcpNoDelay(httpParameters, true);
mClient = new DefaultHttpClient(httpParameters);
}
}
/*
*Grab the full source
*/
public String grabSource(String url) {
mBuffer.setLength(0);
InitializeClient();
String source = "";
try {
mRequest.setURI(new URI(url));
HttpResponse response = mClient.execute(mRequest);
mReader = new BufferedReader(new InputStreamReader(response
.getEntity().getContent()));
String line = "";
while ((line = mReader.readLine()) != null) {
mBuffer.append(line);
mBuffer.append(mNewLine);
source = mBuffer.toString();
if (Thread.interrupted()) {
break;
}
}
} catch (ConnectTimeoutException e) {
source = "Connection Timed Out.";
} catch (java.net.UnknownHostException e) {
source = "No Internet Connection available!";
} catch (java.lang.ArrayIndexOutOfBoundsException e) {
source = "Site Parsing Exception.";
} catch (ClientProtocolException e) {
source = "Protocol Exception.";
} catch (IOException e) {
source = "Server not responding.";
} catch (URISyntaxException e) {
source = "Wrong URL!";
} catch (Exception e) {
source = "Exception - " + e.toString() + " - "
+ e.getMessage();
e.printStackTrace();
} finally {
closeReader();
}
return source;
}
}
First of all, I would not recommend on using HTTPClient any more, since it is not supported any more from sdk version 23.
So, it will be better to migrate the network operations to URL Connection.
Now, android never allows network operations on Main thread since it will block the UI thread for a considerable time, hence may cause crash or bad user experience.
You can take a look on these docs : Doc 1
The better way to do Network operations is by creating an AsyncTask.
Just take care not to access any UI thread element in the doInBackground method. You can modify UI Thread elements on onPreExecute or onPostExecute Methods.
I have created a NetworkOps Util. You can take a look on that, whether it may be any use for you :
import android.content.Context;
import android.net.Uri;
import android.util.Log;
import com.csehelper.variables.Constants;
import com.csehelper.variables.Keys;
import com.csehelper.variables.Url;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.ProtocolException;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.util.ArrayList;
public class NetworkOps {
public final String EXCEPTION = "~Exception~";
/****************************
* Method to Grab Source
****************************/
public static String GrabSource(String URL) {
return PostData(URL, null);
}
/**
* *****************************************
* Method to Grab Source code from URL
* Posting Data
* *****************************************
*/
private static String PostData(String url, Uri.Builder uribuilder) {
String Source;
HttpURLConnection.setFollowRedirects(false);
HttpURLConnection urlConnection = null;
try {
urlConnection = (HttpURLConnection) new URL(url).openConnection();
urlConnection.setDoOutput(true);
urlConnection.setConnectTimeout(10000);
if(uribuilder != null) {
String query = uribuilder.build().getEncodedQuery();
OutputStream os = urlConnection.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(query);
writer.flush();
writer.close();
os.close();
}
urlConnection.connect();
if (urlConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
String line;
StringBuilder builder = new StringBuilder();
InputStreamReader isr = new InputStreamReader(
urlConnection.getInputStream());
BufferedReader reader = new BufferedReader(isr);
while ((line = reader.readLine()) != null) {
builder.append(line);
}
Source = builder.toString();
} else {
Source = EXCEPTION + "Server unreachable. Check network connection.";
}
} catch (SocketTimeoutException e) {
Source = EXCEPTION + "Connection timed out.";
} catch (java.net.UnknownHostException e) {
Source = EXCEPTION + Constants.EXCEPTION_NO_NET;
} catch (ArrayIndexOutOfBoundsException e) {
Source = EXCEPTION + "Server error";
} catch (ProtocolException e) {
Source = EXCEPTION + "Protocol error";
} catch (IOException e) {
Source = EXCEPTION + "Server unreachable. Check network connection.";
} catch (Exception e) {
Source = EXCEPTION + "Error:" + e.toString() + " - "
+ e.getMessage();
e.printStackTrace();
} finally {
if (urlConnection != null) urlConnection.disconnect();
}
return Source;
}
}
Call these Static Functions from AsyncTask:
/*********************************
* AsyncTask to GrabSource
********************************/
class AsyncTask_GrabSource extends AsyncTask<Void, Void, Void> {
String Source = null;
String url = "https://enigmatic-woodland-35608.herokuapp.com/pager.json";
#Override
protected void onPreExecute() {
//Runs on Main Thread. You can access your UI elements here.
}
#Override
protected Void doInBackground(Void... params) {
// Don't access any UI elements from this function
Source = NetworkOps.GrabSource(this.url);
return null;
}
#Override
protected void onPostExecute(Void result) {
if (Source != null) {
if (!Source.contains("~Exception~")) {
//Show Error Message or do whatever you want
} else {
//Do Whatever with your Grabbed Sourcecode.
// This function runs on UI Thread, so you can update UI elements here
}
}
}
You can also post data with the function PostData. In method doInBackground, add this:
Uri.Builder builder = new Uri.Builder()
.appendQueryParameter("key", "value")
.appendQueryParameter("key2", "value2");
Source = NetworkOps.PostData(getApplicationContext(), url, builder);

How can i handle exception when i use asynctask in android?

Explanation:
I am using a web service for my application.In which, every request is >using GET method. so create a class in which I also create method to set >the url and get the response from the server.
Here, is my class which get the response from server.
package adapter;
import android.content.Context;
import android.util.Log;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.UnknownHostException;
public class CallAPI {
private Context context;
public String GetResponseGetMethod(String url) {
URL obj;
String Response="";
String getMethodResponse = "";
try {
obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("GET");
int responseCode = con.getResponseCode();
Log.e("GET Response Code :: " , ""+responseCode);
if (responseCode == HttpURLConnection.HTTP_OK) { // success
BufferedReader in = new BufferedReader(new InputStreamReader(
con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine+"\n");
}
in.close();
// print result
getMethodResponse=response.toString();
Log.e("Response",response.toString());
} else {
Log.e("GET request not worked","");
}
}
catch (MalformedURLException e) {
Toast.makeText(context, "YEs got it", Toast.LENGTH_LONG).show();
}
catch (IOException e){
Toast.makeText(context, "YEs Inside IO it", Toast.LENGTH_LONG).show();
}
return getMethodResponse;
}
}
Above class get response.
Here is my class where I used Asynktask
public class TabJson extends AsyncTask<String, String, String> {
String jsonStr = "";
#Override
protected void onPreExecute() {
Utils.Pdialog(getContext());
}
#Override
protected String doInBackground(String... params) {
jsonStr = new CallAPI().GetResponseGetMethod(url);
if (jsonStr != null) {
try {
JSONObject obj = new JSONObject(jsonStr);
} catch (JSONException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
}
}
Sometimes it takes to time to get response.
MyQuestion is:
How can I handle this situation when it takes too time to get response.It >also raised an exception like unknowhostapi.
How can I overcome from this problem.Please, help me to solve out this problem.
#Milan in your callAPI class assign some value to getMehodResponse in catch blocks as follows-
public class CallAPI {
private Context context;
public String GetResponseGetMethod(String url) {
URL obj;
String Response="";
String getMethodResponse = "";
try {
obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("GET");
int responseCode = con.getResponseCode();
Log.e("GET Response Code :: " , ""+responseCode);
if (responseCode == HttpURLConnection.HTTP_OK) { // success
BufferedReader in = new BufferedReader(new InputStreamReader(
con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine+"\n");
}
in.close();
// print result
getMethodResponse=response.toString();
Log.e("Response",response.toString());
} else {
Log.e("GET request not worked","");
}
}
catch (MalformedURLException e) {
getMethodResponse="Malformed";
Toast.makeText(context, "YEs got it", Toast.LENGTH_LONG).show();
}
catch (IOException e){
getMethodResponse="IO";
Toast.makeText(context, "YEs Inside IO it", Toast.LENGTH_LONG).show();
}
return getMethodResponse;
}
}
In TabJson class return following in doInBackground method-
#Override
protected String doInBackground(String... params) {
jsonStr = new CallAPI().GetResponseGetMethod(url);
return jsonStr;
}
In TabJson class use following code in onPostExecute method-
#Override
protected void onPostExecute(String s) {
if (s != null) {
try {
JSONObject obj = new JSONObject(jsonStr);
} catch (JSONException e) {
e.printStackTrace();
//Show pop up or alert msg here.
}
}
switch(s){
case "IO":
//Do what you want to show your user.
break;
case "Malformed":
//Do what you want to show your user.
break;
}
super.onPostExecute(s);
}
#Milan I'm not seeing any AsyncTask in your code. If you want to implement AsyncTask task follow these steps-
1.extend AsyncTask
2.override doInBackground() and postExecute method.
do your work in doInBackground and get response from server.
in postExecute handle your exeption according to your response status.
You'll have to make your function that deals with the server return some object that can contain all possible results, not just the success case. So for example:
class Results {
public String result;
public Err error;
public enum Err {
OK, ERR1, ERR2, ERR3
}
}
So if everything is OK, you set the result string to the response and the error enum to OK. Or if there is some other error, use another enum of your definition. In you code that receives the result, you can check the error type to determine what to do with it.
There are some issues with your code:
protected String doInBackground(String... params) {
jsonStr = new CallAPI().GetResponseGetMethod(url);
if (jsonStr != null) {
try {
JSONObject obj = new JSONObject(jsonStr);
} catch (JSONException e) {
e.printStackTrace();
}
}
return null;
}
You are returning null. Returning string instead.
protected String doInBackground(String... params) {
jsonStr = new CallAPI().GetResponseGetMethod(url);
return jsonStr;
}
Now, in post execute, format it in jsonObject like this:
#Override
protected void onPostExecute(String s) {
if (s != null) {
try {
JSONObject obj = new JSONObject(s);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
Now, you have JSONobject obj. Do something with it.
use Async Task and also add permission of internet in your manifest file.
<uses-permission android:name="android.permission.INTERNET" />

UrlConnection working with Java code but not for Android - use in Digest Authenticated Server

I'm using URLConnection to connect to the main server. The server implements digest authentication. If I connect to the server with java library, the connection is successful. But if I use the same code for android, the connection is rejected for the reason - username and password do not match.
Here is the code for my Java project:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.Authenticator;
import java.net.PasswordAuthentication;
import java.net.URL;
import java.net.URLConnection;
public class Connect {
static StringBuilder sb;
public static void main(String args[]) {
String strURL = "http://hostserver/";
final String username = "username";
final String password = "password";
Authenticator.setDefault(new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
PasswordAuthentication pa = new PasswordAuthentication (username, password.toCharArray());
System.out.println(pa.getUserName() + ":" + new String(pa.getPassword()));
return pa;
}
});
BufferedReader in = null;
StringBuffer sb = new StringBuffer();
try {
URL url = new URL(strURL);
URLConnection connection = url.openConnection();
in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
sb.append(line);
}
} catch (java.net.ProtocolException e) {
sb.append("User Or Password is wrong!");
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (in != null) {
in.close();
}
} catch (Exception e) {
System.out.println("Exception");
}
}
System.out.println("The Data is: " + sb.toString());
}
}
The above code works fine and I'm able to connect to my host server which is implementing digest authentication. I'm unable to use the same code for Android to connect. Here is my android code:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.Authenticator;
import java.net.PasswordAuthentication;
import java.net.URL;
import java.net.URLConnection;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
public class Connect extends Activity {
static StringBuilder sb;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
String strURL = "http://hostserver/";
final String username = "username";
final String password = "password";
Authenticator.setDefault(new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
PasswordAuthentication pa = new PasswordAuthentication (username, password.toCharArray());
// System.out.println(pa.getUserName() + ":" + new String(pa.getPassword()));
return pa;
}
});
BufferedReader in = null;
StringBuffer sb = new StringBuffer();
try {
URL url = new URL(strURL);
URLConnection connection = url.openConnection();
in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
sb.append(line);
}
} catch (java.net.ProtocolException e) {
sb.append("User Or Password is wrong!");
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (in != null) {
in.close();
}
} catch (Exception e) {
System.out.println("Exception");
}
}
Log.d("DATA", sb.toString());
}
}
If the same code works for Java, it should also work for Android.
The code loops in the Authenticator as it finds username and password not matching in the Android code for some reason which in fact are correct. The code runs perfect for Java project.
while ((line = in.readLine()) != null) {
sb.append(line);
}
remove this code and write just
line = in.readLine().toString();
sb.append(line);
Check Issue 9579: Connection to server with Digest Authentication not working.
http://bethecoder.com/applications/tutorials/tools-and-libs/commons-http-client/digest-authentication.html
I found this site to be helpful.

Categories

Resources