In my app, I am using broadcast receiver to capture the internet connect and disconnect state. Its working fine. Here is the code:
public class CheckConnectivity extends BroadcastReceiver{
#Override
public void onReceive(Context context, Intent arg1) {
boolean isNotConnected = arg1.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, false);
if(isNotConnected){
Toast.makeText(context, "Disconnected", Toast.LENGTH_LONG).show();
}
else
{
Toast.makeText(context, "Connected", Toast.LENGTH_LONG).show();
}
}
}
I am using http web services in my app. I wrote them in different class.
HttpConnect.java:
public class HttpConnect {
public static String finalResponse;
public static HttpURLConnection con = null;
public static String sendGet(String url) {
try {
StringBuffer response = null;
//String urlEncode = URLEncoder.encode(url, "UTF-8");
URL obj = new URL(url);
Log.e("url", obj.toString());
con = (HttpURLConnection) obj.openConnection();
// optional default is GET
con.setRequestMethod("GET");
//add request header
con.setConnectTimeout(10000);
int responseCode = con.getResponseCode();
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
finalResponse = response.toString();
} catch (IOException e) {
e.printStackTrace();
}
//print result
return finalResponse;
}
}
My problem is, how to disconnect or cancel http request when broadcast receiver says no connectivity.
I have tried this code below:
if(isNotConnected){
Toast.makeText(context, "Disconnected", Toast.LENGTH_LONG).show();
if(HttpConnect.con != null)
{
HttpConnect.con.disconnect();
}
}
But its not working. Can anybody tell me how to cancel http request when broadcast receiver captures lost connection?
You should create one method like as below:
public static boolean isOnline(Context mContext) {
ConnectivityManager cm = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting()) {
return true;
}
return false;
}
And before your http call, you should just check, if it returns true, it means internet is available and if it is false, it means internet not available and you can stop your http call.
Also, if your call is already initiated, you should set request timeout value there like 30 seconds, if there is no internet, you will get exception of TimeoutError
Related
Hi I need to display the message "Data not Received" on connection or read Timeout.
I implement this using java.net.SocketTimeoutException but can't get message if there is no data received while internet connected.
I get only help through the internet connected or not.
But actually I want to get it when the internet is connected.
Internet Connectivity Test Code
public static boolean isNetworkConnected(Activity activity) {
ConnectivityManager connectivity = (ConnectivityManager) activity.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity != null) {
NetworkInfo[] info = connectivity.getAllNetworkInfo();
if (info != null)
for (int i = 0; i < info.length; i++)
if (info[i].getState() == NetworkInfo.State.CONNECTED) {
return true;
}
}
return false;
}
Code
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
String result = "";
try {
URL url = new URL(params[0]);
httpConnection = (HttpURLConnection) url.openConnection();
httpConnection.setRequestProperty("Accept", "application/json");
httpConnection.setReadTimeout(10000);
httpConnection.setConnectTimeout(15000);
httpConnection.setRequestMethod("POST");
httpConnection.setDoInput(true);
httpConnection.setDoOutput(true);
OutputStream os = httpConnection.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
writer.write(String.valueOf(values));
writer.flush();
writer.close();
os.close();
int responseCode = httpConnection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
InputStream iStream = httpConnection.getInputStream();
InputStreamReader isReader = new InputStreamReader(iStream);
BufferedReader br = new BufferedReader(isReader);
String line;
while ((line = br.readLine()) != null) {
result += line;
}
}
} catch (java.net.SocketTimeoutException e) {
Toast.makeText(context, "Network Error : No Data Received.", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
Log.e("Error : ", e.toString());
}
return result;
}
For displaying Toast:
catch (java.net.SocketTimeoutException e) {
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(context, "Network Error : No Data Received.", Toast.LENGTH_SHORT).show();
}
});
}
catch (Exception e) {
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(context,e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
I wanna get some data from server with this code :
public class Webservice {
public static String readUrl(String url, ArrayList<NameValuePair> params) {
try {
HttpClient client = new DefaultHttpClient();
HttpPost method = new HttpPost(url);
if (params != null) {
method.setEntity(new UrlEncodedFormEntity(params));
}
HttpResponse response = client.execute(method);
InputStream inputStream = response.getEntity().getContent();
String result = convertInputStreamToString(inputStream);
return result;
}
catch (ClientProtocolException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
return null;
}
private static String convertInputStreamToString(InputStream inputStream) {
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder builder = new StringBuilder();
String line = "";
while ((line = reader.readLine()) != null) {
builder.append(line);
}
return builder.toString();
}
catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
but there is some delay and pause in the application , so i wanna run this code in the Thread , but when i tried to do it , i got some error , for example i couldn't return the result or ...
Take a look at AsyncTask:
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. The AsyncTask class provides one of
the simplest ways to fire off a new task from the UI thread. For more
discussion of this topic, see the blog post Multithreading For
Performance.
In the following snippet, the myClickHandler() method invokes new
DownloadWebpageTask().execute(stringUrl). The DownloadWebpageTask
class is a subclass of AsyncTask.
public class HttpExampleActivity extends Activity {
private static final String DEBUG_TAG = "HttpExample";
private EditText urlText;
private TextView textView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
urlText = (EditText) findViewById(R.id.myUrl);
textView = (TextView) findViewById(R.id.myText);
}
// When user clicks button, calls AsyncTask.
// Before attempting to fetch the URL, makes sure that there is a network connection.
public void myClickHandler(View view) {
// Gets the URL from the UI's text field.
String stringUrl = urlText.getText().toString();
ConnectivityManager connMgr = (ConnectivityManager)
getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
new DownloadWebpageTask().execute(stringUrl);
} else {
textView.setText("No network connection available.");
}
}
// Uses AsyncTask to create a task away from the main UI thread. This task takes a
// URL string and uses it to create an HttpUrlConnection. Once the connection
// has been established, the AsyncTask downloads the contents of the webpage as
// an InputStream. Finally, the InputStream is converted into a string, which is
// displayed in the UI by the AsyncTask's onPostExecute method.
private class DownloadWebpageTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
// params comes from the execute() call: params[0] is the url.
try {
return downloadUrl(urls[0]);
} catch (IOException e) {
return "Unable to retrieve web page. URL may be invalid.";
}
}
// onPostExecute displays the results of the AsyncTask.
#Override
protected void onPostExecute(String result) {
textView.setText(result);
}
}
... }
I try to write an android program to check internet connection with two different methods. The first one is the most common method, CheckInternetConnection(), and the second method is through connecting to a website, ConnectGoogleTest().
The first one work perfectly, but in the second one my tablet hang! anybody knows why ?
The codes are:
public class myITClass {
private Context ctx ;
public myITClass(Context context){
this.ctx = context;
}
public boolean CheckInternetConnection() {
ConnectivityManager cm = (ConnectivityManager) ctx.getSystemService(Context.CONNECTIVITY_SERVICE);
//NetworkInfo ni = cm.getActiveNetworkInfo();
if (cm.getActiveNetworkInfo() == null) {
// There are no active networks.
return false;
} else {
return true;
}
}
public boolean googlePingTest(){
boolean res = false ;
try {
URL url = new URL("http://www.google.com/");
HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
urlc.setConnectTimeout(15000);
urlc.connect();
if (urlc.getResponseCode() == 200) { res = true; }
} catch (MalformedURLException e1) {
res = false;
} catch (IOException e) {
res = false ;
}catch (Exception e){
res = false ;
}
return res;
}
}
You can send a ping to http://www.google.com/ through HttpURLConnection. Please make sure that you doing it in the background thread. Creating a network task must be run in the background. There are 3 options to do that:
Using AsyncTask
Using IntentService
Using Service
In this time, we will use AsyncTask. So create a private class inside your Activity:
private boolean res = false;
private class PingTask extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... urlSite) {
HttpURLConnection urlc = null;
try {
URL url = new URL("http://www.google.com/");
urlc = (HttpURLConnection) url.openConnection();
urlc.setConnectTimeout(15000);
urlc.setRequestMethod("GET");
urlc.connect();
if (urlc.getResponseCode() == 200) { res = true; }
} catch (MalformedURLException e1) {
res = false;
} catch (IOException e) {
res = false ;
}catch (Exception e){
res = false ;
}finally{
if (urlc != null) {
try{
// close the connection
urlc.disconnect();
}catch (Exception e){
e.printStackTrace();
}
}
}
return null;
}
}
Don't forget to add this field in your class:
private boolean res = false;
Create a method to get the status:
public boolean getStatus(){
return status;
}
How to use?
Execute the PingTask first to check the status:
PingTask ping = new PingTask();
ping.execute();
Get the status:
// if the connection is available
if(getStatus()==true){
// do your thing here.
}
The second method calls network synchronously on main thread, and that blocks the UI. Try using AsyncTask for it.
I have an app where i read some data from online api every 30sec. I have somewhat secured my app so that it will check if the device is connected to network and data can be trasfered.
private boolean isNetworkAvailable() {
ConnectivityManager connectivityManager
= (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
But this does not include situations when i am connected to a network which needs authentification for internet access. Or when you have only local connectivity enabled.
The app tries to get data from that api and it crashes. Here is the request code:
public static JSONObject requestWebService(String serviceUrl) {
disableConnectionReuseIfNecessary();
HttpURLConnection urlConnection = null;
try {
// create connection
URL urlToRequest = new URL(serviceUrl);
urlConnection = (HttpURLConnection)urlToRequest.openConnection();
urlConnection.setConnectTimeout(10000);
urlConnection.setReadTimeout(10000);
// handle issues
int statusCode = urlConnection.getResponseCode();
if (statusCode == HttpURLConnection.HTTP_UNAUTHORIZED) {
// handle unauthorized (if service requires user login)
} else if (statusCode != HttpURLConnection.HTTP_OK) {
// handle any other errors, like 404, 500,..
}
// create JSON object from content
InputStream in = new BufferedInputStream(
urlConnection.getInputStream());
return new JSONObject(getResponseText(in));
} catch (MalformedURLException e) {
// URL is invalid
} catch (SocketTimeoutException e) {
// data retrieval or connection timed out
} catch (IOException e) {
// could not read response body
// (could not create input stream)
} catch (JSONException e) {
// response body is no valid JSON string
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
}
return null;
}
All i need is that this app will not crash. How can i achieve this?
SOLUTION: it needed null check before reading JSON object... it was in different method:
public void check(){
JSONArray jsonArray = null;
if(isNetworkAvailable()) {
JSONObject dataZNetu = requestWebService("http://census.soe.com/get/ps2:v2/world_event?type=METAGAME");
if(dataZNetu != null) { //THIS WAS THE SOLUTION TO MY PROBLEM
try {
jsonArray = dataZNetu.getJSONArray("world_event_list");
for (int i = jsonArray.length() - 1; i >= 0; i--) {
JSONObject tempObj = jsonArray.getJSONObject(i);
int worldId = tempObj.getInt("world_id");
int stateID = tempObj.getInt("metagame_event_state");
int eventType = tempObj.getInt("metagame_event_id");
int instanceId = tempObj.getInt("instance_id");
checkUIchange(worldId, stateID, eventType, instanceId);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
Since it looks like you are catching the appropriate exceptions, I'm guessing that the crash is in the code that calls this method.
If it tries to do something with the result, without checking for null, that's the problem.
But of course, knowing exactly where it crashes would help.
I am making a login app to retreive some information from the link that appears in the code. My problem is that I'm getting a "400 Bad request. Your browser sent a request that this server could not understand. [...] Server at idp.tut.fi Port 443" in the Log file.
Besides, that link handles RC4_128 with SHA1 for authentication and RSA for key exchange but don't really know where I can apply those protocols in my code.
Thanks for your help!
This is my code:
public class POPLogin extends Activity {
private EditText usr, pass;
private Button submitButton;
private CharSequence notify;
private String res, resp;
private final String link = "https://idp.tut.fi/idp/Authn/UserPassword";
private URL url;
public static boolean isNetworkAvailable(Context context) {
return ((ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo() != null;
}
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_poplogin);
usr = ((EditText) findViewById(R.id.usernameField));
pass = ((EditText) findViewById(R.id.passwordField));
submitButton = (Button) findViewById(R.id.submitButton);
submitButton.getBackground().setColorFilter(new LightingColorFilter(0x00FFB90F, 0xFFAA0000));
/*
* This method controls the login button so that the correct
* information is sent to the server.
*/
submitButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if(isNetworkAvailable(getApplicationContext())) { // If there is an Internet connection available
/*
* A new thread is created from the main one
* to separate the login process (AsyncTask, https operations).
*/
new Thread(new Runnable() {
public void run() {
try {
url = new URL(link);
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
// Create the SSL Connection
SSLContext sc;
sc = SSLContext.getInstance("TLS");
sc.init(null, null, new java.security.SecureRandom());
conn.setSSLSocketFactory(sc.getSocketFactory());
// SSL Authentication
String userpass = usr.getText().toString() + ":" + pass.getText().toString();
String basicAuth = "Basic " + Base64.encodeToString(userpass.getBytes(), Base64.DEFAULT);
conn.setRequestProperty("Authorization", basicAuth);
Log.i("NOTIFICATION", "All SSL parameters set");
// Set timeout and method
conn.setReadTimeout(7000);
conn.setConnectTimeout(7000);
conn.setRequestMethod("POST");
conn.setDoInput(true); // Flag indicating this connection is used for output (POST)
conn.connect();
Log.i("NOTIFICATION", "Connection request sent");
// Check HTTP Response Code
int status = conn.getResponseCode();
InputStream is;
if (status >= 400 ) {
is = conn.getErrorStream();
} else {
is = conn.getInputStream();
}
Log.i("NOTIFICATION", "HTTP Code Checked");
// Receives the answer
resp = null;
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
while((res = rd.readLine()) != null) {
resp += res;
}
Log.i("NOTIFICATION", "Answer received");
Log.i("CODE", resp);
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
} else {
notify = "Internet Connection not available";
}
if(notify != null) {
Toast toast = Toast.makeText(getApplicationContext(), notify, Toast.LENGTH_SHORT);
toast.show();
notify = null;
}
}
});
}
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.poplogin, menu);
return true;
}
}
If you got an HTTP error code it is proof that your HTTPS and therefore SSL setup is working perfectly.
The problem is in the data you're sending. It looks like you need to use a java.net.Authenticator rather than try to do it by hand.