I am making an app in android studio in which i am getting data from JSON files and populating it in a spinner. Below is my image of app
I have two options for saving data with the following conditions.
When internet is off the data will be saved into a local xml file.
When internet is on the app will check for the connectivity and if available then it will check the file and then upload it to the server.
For now i am able to implement the both points separately i.e. I have created a method which will check for the connectivity of the internet. Passed this method into a condition and if the connection is available it will save the data into a local file aka xml file and if internet is not available then it will save the new data only to the server.
My script is below
require_once ('config.php');
$return_arr = array();
$ref_no = ($_POST['ref_no']);
$meter_type = ($_POST['meter_type']);
$lattitude = ($_POST['lattitude']);
$longitude = ($_POST['longitude']);
$site_status = ($_POST['site_status']);
$comm_status = ($_POST['comm_status']);
$pole_type = ($_POST['pole_type']);
$meter_placement = ($_POST['meter_placement']);
$date_time = ($_POST['datetime']);
$record_save = "INSERT INTO `survey`(`s_id`,`ref_no`,`meter_type`, `lattitude`,`longitude`,`site_status`,`comm_status`,`pole_type`,`meter_placement`, `datetime`) values (NULL,'".$ref_no."','".$meter_type."','".$lattitude."','".$longitude."','".$site_status."','".$comm_status."','".$pole_type."','".$meter_placement."','".$date_time."')";
mysqli_query ($con,$record_save);
$row_array['errorcode1'] = 1;
I am saving all the data in a string format like below
String DateTime,refr_no, meter_type, Latitude, Longitude, site_status, comm_status, pole_type,rb_text;
On button click i am asking a permission for saving file in local storage and then on permission granted i have placed checks like below
btn_save_data.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(refr_no == "Select a reference number" || meter_type == "Select Meter Type" || Latitude == " " || Longitude == ""
|| site_status == "Select Site Status" || comm_status == "" || pole_type == "Select pole type" || DateTime == "" )
{
Toast.makeText(MainActivity.this, " Data not saved.... you must be missing some thing.. Please check!!! " , Toast.LENGTH_LONG ).show();
}else {
new TedPermission(MainActivity.this)
.setPermissionListener(ListenerSaveData)
.setRationaleMessage("This activity will need your permission to save file ")
.setPermissions(Manifest.permission.WRITE_EXTERNAL_STORAGE)
.check();
Toast.makeText(MainActivity.this,"Data saved successfully", Toast.LENGTH_SHORT).show();
}
}
});
final PermissionListener ListenerSaveData = new PermissionListener() {
#Override
public void onPermissionGranted() {
if(refr_no == "Select a reference number" || meter_type == "Select Meter Type" || Latitude == " " || Longitude == ""
|| site_status == "Select Site Status" || comm_status == "" || pole_type == "Select pole type" || DateTime == "" )
{
Toast.makeText(MainActivity.this, " Data not saved.... you must be missing some thing.. Please check!!! " , Toast.LENGTH_LONG ).show();
}else {
if (!isOnline()) {
try {
File file = new File(getApplicationContext().getExternalFilesDir(null), filename);
file.createNewFile();
FileOutputStream fileos = new FileOutputStream(file, true);
XmlSerializer xmlSerializer = Xml.newSerializer();
StringWriter writer = new StringWriter();
xmlSerializer.setOutput(writer);
xmlSerializer.startDocument("UTF-8", true);
xmlSerializer.startTag(null, "record");
xmlSerializer.startTag(null, "ref_no");
xmlSerializer.text(refr_no);
xmlSerializer.endTag(null, "ref_no");
xmlSerializer.startTag(null, "meter_type");
xmlSerializer.text(meter_type);
xmlSerializer.endTag(null, "meter_type");
xmlSerializer.startTag(null, "lat");
xmlSerializer.text(Latitude);
xmlSerializer.endTag(null, "lat");
xmlSerializer.startTag(null, "long");
xmlSerializer.text(Longitude);
xmlSerializer.endTag(null, "long");
xmlSerializer.startTag(null, "site_status");
xmlSerializer.text(site_status);
xmlSerializer.endTag(null, "site_status");
xmlSerializer.startTag(null, "communication_status");
xmlSerializer.text(comm_status);
xmlSerializer.endTag(null, "communication_status");
xmlSerializer.startTag(null, "pole_type");
xmlSerializer.text(pole_type);
xmlSerializer.endTag(null, "pole_type");
xmlSerializer.startTag(null, "meter_placement");
xmlSerializer.text(rb_text);
xmlSerializer.endTag(null, "meter_placement");
xmlSerializer.startTag(null, "date_time");
xmlSerializer.text(DateTime);
xmlSerializer.endTag(null, "date_time");
xmlSerializer.endTag(null, "record");
xmlSerializer.endDocument();
xmlSerializer.flush();
String dataWrite = writer.toString();
fileos.write(dataWrite.getBytes());
fileos.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
dd_ref.setSelection(0);
dd_pole_type.setSelection(0);
dd_site_status.setSelection(0);
dd_m_type.setSelection(0);
_latitude.setText("");
_longitude.setText("");
comment.setText("");
DateTime = "";
refr_no = "";
Latitude = "";
Longitude = "";
site_status = "";
comm_status = "";
pole_type = "";
rb_text = "";
rg_meter_placement.clearCheck();
}else if (isOnline())
{
new SaveData().execute(refr_no,meter_type,Latitude,Longitude,site_status,comm_status,pole_type,rb_text,DateTime);
}
}
}
#Override
public void onPermissionDenied(ArrayList<String> deniedPermissions) {
}
};
Here the isOnline method is checking the internet connectivity as below
protected boolean isOnline() {
ConnectivityManager cm = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if(netInfo != null && netInfo.isConnectedOrConnecting())
{
Toast.makeText(MainActivity.this, "Internet is Connected", Toast.LENGTH_SHORT).show();
return true;
}
else {
Toast.makeText(MainActivity.this, "Internet is NOT Connected", Toast.LENGTH_SHORT).show();
return false;
}
}
For SaveData() method the code is below
private class SaveData extends AsyncTask<String, Void, String>{
ProgressDialog mProgressDialog;
String res;
#Override
protected void onPreExecute() {
mProgressDialog = ProgressDialog.show(MainActivity.this,
"", "Saving Data Please wait...");
mProgressDialog.show();
}
#Override
protected String doInBackground(String... params) {
res = null;
PutUtility put = new PutUtility();
put.setParam("ref_no",params[0].toString());
put.setParam("meter_type", params[1].toString());
put.setParam("lattitude", params[2].toString());
put.setParam("longitude", params[3].toString());
put.setParam("site_status",params[4].toString());
put.setParam("comm_status",params[5].toString());
put.setParam("pole_type",params[6].toString());
put.setParam("meter_placement",params[7].toString());
put.setParam("datetime",params[8].toString());
try {
res = put.postData("http://192.168.100.12:8000/new/post_data.php");
Log.v("res", res);
} catch (Exception e) {
e.printStackTrace();
}
return res;
}
protected void onPostExecute(String res) {
if(refr_no == "Select a reference number" || meter_type == "Select Meter Type" || Latitude == " " || Longitude == ""
|| site_status == "Select Site Status" || comm_status == "" || pole_type == "Select pole type" || DateTime == "" )
{
Toast.makeText(MainActivity.this, " Data not saved.... you must be missing some thing.. Please check!!! " , Toast.LENGTH_LONG ).show();
}else {
Toast.makeText(getApplicationContext(), " Data Saved Successfully ", Toast.LENGTH_SHORT).show();
dd_ref.setSelection(0);
dd_pole_type.setSelection(0);
dd_site_status.setSelection(0);
dd_m_type.setSelection(0);
_latitude.setText("");
_longitude.setText("");
comment.setText("");
DateTime = "";
refr_no = "";
Latitude = "";
Longitude = "";
site_status = "";
comm_status = "";
pole_type = "";
rb_text = "";
rg_meter_placement.clearCheck();
}
mProgressDialog.dismiss();
Intent intent = getIntent();
finish();
startActivity(intent);
}
}
While the PutUtility class is below
public class PutUtility {
private Map<String, String> params = new HashMap<>();
private static HttpURLConnection httpConnection;
private static BufferedReader reader;
private StringBuffer response;
public void setParam(String key, String value) {
params.put(key, value);
}
public String postData(String Url) {
StringBuilder sb = new StringBuilder();
for (String key : params.keySet()) {
String value = null;
value = params.get(key);
if (sb.length() > 0) {
sb.append("&");
}
sb.append(key + "=" + value);
}
try {
// Defined URL where to send data
URL url = new URL(Url);
URLConnection conn = null;
conn = url.openConnection();
// Send POST data request
httpConnection = (HttpURLConnection) conn;
httpConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
httpConnection.setRequestMethod("POST");
httpConnection.setDoInput(true);
httpConnection.setDoOutput(true);
OutputStreamWriter wr = null;
wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(sb.toString());
wr.flush();
BufferedReader in = new BufferedReader(
new InputStreamReader(httpConnection.getInputStream()));
String inputLine;
response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return response.toString();
}}
I want to implement the second point that whenever the app is connected to the internet then all the data in the file (xml file) will be uploaded to the server.
As a newbie i don't have any idea how to do it.
Any help would be highly appreciated.
Related
After execution for 5 to 6 times i am not able to get response and the message is also not going to gateway and the application get struck.At InputStreamReader i am not able to get any response after execution for 5 times.When i checked the logs no error is coming but the Input Stream is not printing.
XMLFunctions.java
public static String getLocalCurtainControlResponse( String ipadress, String imvgid, String deviceid, String command, String value, int slidedValue) {
String result = null;
BufferedReader reader =null;
System.out.println("getLocalCurtainControlResponse : IN");
System.out.println("command : " + command);
System.out.println("value : " + value);
byte[] loginBytes = ("admin" + ":" + "admin").getBytes();
StringBuilder loginBuilder = new StringBuilder()
.append("Basic ")
.append(Base64.encodeToString(loginBytes, Base64.DEFAULT));
try {
URL url = new URL("http://" + ipadress + "/cgi-bin/WebInterface.cgi?ImvgId=" + imvgid + "%20&DeviceId=" + deviceid + "%20&Action=" + command + "%20&Value=" + value + "%20&Level=" + slidedValue + "%20&App=MID");
System.out.print("step0"+"http://" + ipadress + "/cgi-bin/WebInterface.cgi?ImvgId=" + imvgid + "%20&DeviceId=" + deviceid + "%20&Action=" + command + "%20&Value=" + value + "%20&Level=" + slidedValue + "%20&App=MID");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// connection.setRequestMethod("GET");
connection.addRequestProperty("Authorization", loginBuilder.toString());
// connection.connect();
InputStream in = connection.getInputStream();
System.out.print("step1"+connection);
StringBuilder sb = new StringBuilder();
System.out.print("step2"+sb);
reader = new BufferedReader(new InputStreamReader(in));
System.out.print("step3"+reader);
String line;
while ((line = reader.readLine()) != null) {
sb.append(line);
sb.append("\n");
}
System.out.print("step4"+sb);
reader.close();
result = sb.toString();
System.out.print("step5"+result);
} catch (MalformedURLException e) {
e.printStackTrace();
System.out.print("Hiiiiiiiiiiiiiiiiiiii"+e.getMessage());
} catch (IOException e) {
e.printStackTrace();
System.out.print("Byeeeeeeeeee"+e.getMessage());
} finally {
if (null!=reader) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
System.out.print("Hellllloooooooo"+e.getMessage());
}
}
}
return result;
}
Find the solution Post and Get using HttpUrlConnection
private Object doSendRequest(final int requestCode, String url, final Object params, final String sessionId, final String requestType, final Activity parentActivity) {
URL myurl;
Log.v("sessionId", sessionId + "");
HttpsURLConnection httpsURLConnection = null;
try {
if (requestType.equalsIgnoreCase("GET")) {
if (params.toString().length() >= 1) {
if (url.contains("?")) {
url = (url + params.toString());
} else {
url = (url + "?" + params.toString());
}
}
}
myurl = new URL(url);
Log.v("RequestCode, URL", requestCode + " : " + url);
httpsURLConnection = (HttpsURLConnection) myurl.openConnection();
httpsURLConnection.setRequestMethod(requestType);
httpsURLConnection.setUseCaches(true);
if (isOnline(parentActivity)) {
httpsURLConnection.addRequestProperty("Cache-Control", "max-age=0");
} else {
httpsURLConnection.setUseCaches(true);
httpsURLConnection.addRequestProperty("Cache-Control", "max-stale=" + CACHE_STALE_TIME_OUT);
httpsURLConnection.addRequestProperty("Cache-Control", "only-if-cached");
}
httpsURLConnection.setConnectTimeout(20 * ONE_SECOND);
httpsURLConnection.setReadTimeout(20 * ONE_SECOND);
httpsURLConnection.setInstanceFollowRedirects(true);
httpsURLConnection.setRequestProperty("Content-Type", CONTENT_TYPE_APPLICATION_JSON);
if (sessionId != null) {
httpsURLConnection.setRequestProperty("sessionId", sessionId);
}
httpsURLConnection.setDoInput(true);
if (!requestType.equalsIgnoreCase("GET")) {
Log.v("RequestData", "" + params.toString());
httpsURLConnection.setDoOutput(true);
BufferedWriter writer = null;
try {
writer = new BufferedWriter(new OutputStreamWriter(httpsURLConnection.getOutputStream(), "UTF-8"));
writer.write(params.toString());
writer.flush();
}catch (Exception e){
e.printStackTrace();
}finally {
if(writer != null){
try {
writer.close();
}catch (Exception e){
e.printStackTrace();
}
}
}
}
httpsURLConnection.connect();
} catch (Exception e) {
Log.v("Ex", "1");
e.printStackTrace();
handleException(requestCode, e, parentActivity);
return null;
}
//---------------------READING THE RESPONSE---------------------------//
BufferedReader bReader = null;
try {
final String newSessionId = httpsURLConnection.getHeaderField("sessionId");
final int httpResponseCode = httpsURLConnection.getResponseCode();
Log.v("Req, Response codes", requestCode+", "+httpResponseCode);
if(httpResponseCode == 504 && !LegionUtils.isOnline(parentActivity)){
parentActivity.runOnUiThread(new Runnable() {
#Override
public void run() {
hideProgressDialog();
showOfflineDialog(parentActivity);
}
});
return null;
}
if (httpResponseCode == 401) {
parentActivity.runOnUiThread(new Runnable() {
#Override
public void run() {
hideProgressDialog();
}
});
return null;
} else if ((httpResponseCode == 400 || (httpResponseCode >= 500 && httpResponseCode <= 599)) && !(parentActivity instanceof CreateAccountActivity)) {
parentActivity.runOnUiThread(new Runnable() {
#Override
public void run() {
hideProgressDialog();
networkCallback.onFailure(requestCode, null);
}
});
return null;
} else if ((httpResponseCode >= 500 && httpResponseCode <= 599) && (parentActivity instanceof CreateAccountActivity)) {
parentActivity.runOnUiThread(new Runnable() {
#Override
public void run() {
networkCallback.onFailure(requestCode, null);
}
});
return null;
}
InputStream inputStream;
try {
inputStream = httpsURLConnection.getInputStream();
}catch (FileNotFoundException e){
e.printStackTrace();
inputStream = httpsURLConnection.getErrorStream();
}
if (inputStream != null) {
bReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
String inputLine;
final StringBuffer response = new StringBuffer();
while ((inputLine = bReader.readLine()) != null) {
response.append(inputLine);
}
bReader.close();
parentActivity.runOnUiThread(new Runnable() {
#Override
public void run() {
Log.v("RESPONSE " + requestCode, response.toString());
networkCallback.onSuccess(requestCode, response.toString(), newSessionId);
}
});
}
} catch (Exception e) {
Log.v("Ex", "2");
e.printStackTrace();
handleException(requestCode, e, parentActivity);
} finally {
try {
if (bReader != null) {
bReader.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
return null;
}
private void handleException(final int requestCode, Exception error, final Activity parentActivity) {
final String errorResponse;
if (error instanceof TimeoutException || error instanceof SocketTimeoutException || error instanceof UnknownHostException) {
errorResponse = "Your request has been timed out. Please try again later.";
} else if (error instanceof SSLException || error instanceof ConnectException) {
errorResponse = null;
parentActivity.runOnUiThread(new Runnable() {
#Override
public void run() {
hideProgressDialog();
showOfflineDialog(parentActivity);
}
});
} /*else if (error instanceof FileNotFoundException) {
errorResponse = "Invalid Request.\nPlease try again later.";
} */else if (error instanceof IOException) {
errorResponse = "Something went wrong. Please try again later.";
} else if (error instanceof JSONException) {
errorResponse = "Unexpected response.\nPlease try again later.";
} else {
errorResponse = null;
parentActivity.runOnUiThread(new Runnable() {
#Override
public void run() {
hideProgressDialog();
showOfflineDialog(parentActivity);
}
});
}
Log.v("FAILURE ERR RESPONSE " + requestCode, errorResponse + "");
parentActivity.runOnUiThread(new Runnable() {
#Override
public void run() {
networkCallback.onFailure(requestCode, errorResponse);
}
});
}
I developed one app and published on playstore also.
Till yestarday the CheckLogin Servlet is working means Login is working file but
from todays mornning it is not working
I am getting following exception
02-27 14:43:23.462 32275-6622/com.dhruva.eprintpost W/System.err: java.io.FileNotFoundException: path of URL
02-27 14:43:23.463 32275-6622/com.dhruva.eprintpost W/System.err: at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:238)
02-27 14:43:23.463 32275-6622/com.dhruva.eprintpost W/System.err: at com.android.okhttp.internal.huc.DelegatingHttpsURLConnection.getInputStream(DelegatingHttpsURLConnection.java:210)
02-27 14:43:23.463 32275-6622/com.dhruva.eprintpost W/System.err: at com.android.okhttp.internal.huc.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java)
02-27 14:43:23.463 32275-6622/com.dhruva.eprintpost W/System.err: at com.dhruva.eprintpost.login.LoginActivity$10.run(LoginActivity.java:513)
02-27 14:43:23.463 32275-6622/com.dhruva.eprintpost W/System.err: at java.lang.Thread.run(Thread.java:818)
and my Login sending request is as follows
new Thread(new Runnable() {
public void run() {
try {
URL url = new URL(SessionManager.getAmateurPath() + "LoginCheck");
Log.v("Urllll",""+url);
URLConnection connection = url.openConnection();
ComStr = "&usrnm=" + email + "&pwd=" + pwd;
str = ComStr.getBytes();
Log.d("inputString", email);
Log.d("inputString", pwd);
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestProperty("Content=length", String.valueOf(str.length));
os = connection.getOutputStream();
os.write(str);
os.flush();
final String status;
final BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
status = in.readLine();
Log.d("Status", status);
runOnUiThread(new Runnable() {
#Override
public void run() {
handleStatus(status, in);
}
});
}
catch (Exception e) {
e.printStackTrace();
}
}
}).start();
use this asynctask
private class SendGcmToServer extends AsyncTask<String, Void, String> {
ProgressDialog dialog;
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
dialog = new ProgressDialog(Activity_Register_Login.this);
dialog.setMessage("Loading....");
dialog.show();
if (regid.isEmpty()) {
Log.e("***************registration_id", regid);
regid = registerInBackground();
}
}
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
String url_for_getdata = Util.register_url;
BufferedReader reader;
String url_data = Util.register_url + "?username=" + editText_user_name.getText().toString() + "&password=" + editText_password.getText().toString() + "&vehId=" + edit_text_vehicle_no.getText().toString() + "®Id=" + regid;
url_data = url_data.replace("\n", "%20");
url_data = url_data.replace(" ", "%20");
url_data = url_data.replace("'", "%20");
System.out.println("url: " + url_data);
try {
URL url = new URL(url_data);
URLConnection conection = url.openConnection();
conection.setConnectTimeout(5000);
conection.setDoOutput(true);
reader = new BufferedReader(new InputStreamReader(conection.getInputStream()));
StringBuilder result = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
result.append(line + "");
}
content = result.toString();
System.out.println(content);
getcontent_for_validate = content;
} catch (Exception e) {
e.printStackTrace();
}
return content;
}
#Override
protected void onPostExecute(String result) {
JSONObject jsonobj;
// TODO Auto-generated method stub
super.onPostExecute(result);
if (result != null) {
if (result.equals("failure")) {
Toast.makeText(context, "Check your Username or Password", Toast.LENGTH_LONG).show();
dialog.dismiss();
} else {//ths is getting data for vehicl_list_unread_count code, client id,restapi_key
try {
Log.d(TAG, "onPostExecute: this inner of post" + getcontent_for_validate);
jsonobj = new JSONObject(getcontent_for_validate);
System.out.println("this is get content" + jsonobj.toString());
JSONArray array = jsonobj.getJSONArray("Staff_Details");
for (int i = 0; i < array.length(); i++) {
Clint_id = editText_user_name.getText().toString();
Api_key = array.getJSONObject(i).getString("api_key");
COMPANY_LOGO = array.getJSONObject(i).getString("company_logo");
Password = editText_password.getText().toString();
}
} catch (JSONException e) {
e.printStackTrace();
}
Database_for_user_details db = new Database_for_user_details(Activity_Register_Login.this);
db.createEntry_for_clint_details(Clint_id, Password, Api_key, "login", edit_text_vehicle_no.getText().toString(), COMPANY_LOGO);
db.createEntry_for_TRIP_STATUS();
Toast.makeText(getApplicationContext(), "Logged-in Successfully", Toast.LENGTH_SHORT).show();
System.out.println("get data" + " " + Clint_id + " " + Api_key);
startActivity(new Intent(Activity_Register_Login.this, Activity_dashboard.class));
dialog.dismiss();
finish();
}
} else {
dialog.dismiss();
Toast.makeText(context, "Check net connection", Toast.LENGTH_LONG).show();
}
}
}
i hope this will help you
all of a sudden my mobile device can't connect to the local server anymore. async tasks are not executed and i just can't figure out why. slowly i'm getting really desperate because in my opinion i didn't change anything to cause this.
as an example, this is a background task which is not working
public class Login extends AsyncTask<String, Void, String>{
private String loginUrl = "http://...";
private int loginSuccess = 0;
public String getToken(String fromJson) throws JSONException {
JSONObject json = new JSONObject(fromJson);
if(json.has("api_authtoken")) {
loginSuccess = 1;
String appToken = json.getString("api_authtoken");
return appToken;
}
else {
return json.toString();
}
}
public String doInBackground(String... arg0) {
// so that they can be closed in the finally block.
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
String authToken;
try {
// get logged in to get the api_authtoken
String email = (String) arg0[0];
String password = (String) arg0[1];
URL url = new URL(loginUrl);
// Create the request and open the connection
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("POST");
urlConnection.setRequestProperty("Content-Type", "application/json");
urlConnection.setRequestProperty("Accept", "application/json");
//put values of edittexts into json-Object
JSONObject data = new JSONObject();
try {
data.put("email", email);
data.put("password", password);
} catch(JSONException e) {
Log.e("EXCEPTION", "unexpected JSON exception", e);
e.printStackTrace();
}
urlConnection.connect();
OutputStreamWriter wr = new OutputStreamWriter(urlConnection.getOutputStream());
wr.write(data.toString());
wr.flush();
reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
//read server response
while((line = reader.readLine()) != null) {
sb.append(line);
}
//receive server "answer"
try {
return getToken(sb.toString());
}catch(JSONException e) {
Log.e("LOG", "unexpected JSON exception", e);
e.printStackTrace();
} finally{
if (urlConnection != null) {
urlConnection.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (final IOException e) {
Log.e("MainActivity", "Error closing stream", e);
}
}
}
//return sb.toString();
return null;
}
catch(IOException e) {
Log.e("LoginTask", "Error ", e);
// If the code didn't successfully get the data, there's no point in attempting
// to parse it.
//forecastJsonStr = null;
return null;
}
}
public void onPostExecute(String result) {
super.onPostExecute(result);
//Log.v("RESULT", result);
if(result == null) {
CharSequence text = "no internet connection";
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(MainActivity.this, text, duration);
toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
toast.show();
}
if(loginSuccess == 0) {
// if the request wasn't successful
// give user a message via toast
CharSequence text = "wrong password or user. please try again";
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(MainActivity.this, text, duration);
toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
toast.show();
}
else {
// save token in shared preferences
SharedPreferences tokenPref = getSharedPreferences(getString(R.string.preference_token), Context.MODE_PRIVATE);
SharedPreferences.Editor editorToken = tokenPref.edit();
editorToken.putString(getString(R.string.saved_auth_token), result);
editorToken.commit();
//save login status = 1 in shared preferences
SharedPreferences loginPref = getSharedPreferences(getString(R.string.preference_logged_in), Context.MODE_PRIVATE);
SharedPreferences.Editor editorLogin = loginPref.edit();
editorLogin.putString(getString(R.string.saved_login), "1");
editorLogin.commit();
Intent mapsIntent = new Intent(getApplicationContext(), MapsActivity.class);
startActivity(mapsIntent);
}
}
}
HttpClient is not supported any more in sdk 23. You have to use URLConnection or downgrade to sdk 22 (compile 'com.android.support:appcompat-v7:22.2.0')
If you need sdk 23, add this to your gradle:
android {
useLibrary 'org.apache.http.legacy'
}
HttpClient won't import in Android Studio
You should think about using a HTTP library, there is a bunch of them on internet, some are really easy to use, optimize and errorless.
For example, Volley (made by Google, I really like this one), okHttp or Picasso (for image).
You should take a look at this.
If you want to send (output), for example with POST or PUT requests you need to use this :-
urlConnection.setDoOutput(true);
In your code :-
public class Login extends AsyncTask<String, Void, String>{
private String loginUrl = "http://...";
private int loginSuccess = 0;
public String getToken(String fromJson) throws JSONException {
JSONObject json = new JSONObject(fromJson);
if(json.has("api_authtoken")) {
loginSuccess = 1;
String appToken = json.getString("api_authtoken");
return appToken;
}
else {
return json.toString();
}
}
public String doInBackground(String... arg0) {
// so that they can be closed in the finally block.
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
String authToken;
try {
// get logged in to get the api_authtoken
String email = (String) arg0[0];
String password = (String) arg0[1];
URL url = new URL(loginUrl);
// Create the request and open the connection
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("POST");
urlConnection.setRequestProperty("Content-Type", "application/json");
urlConnection.setRequestProperty("Accept", "application/json");
urlConnection.setDoOutput(true); // HERE
//put values of edittexts into json-Object
JSONObject data = new JSONObject();
try {
data.put("email", email);
data.put("password", password);
} catch(JSONException e) {
Log.e("EXCEPTION", "unexpected JSON exception", e);
e.printStackTrace();
}
OutputStreamWriter wr = new OutputStreamWriter(urlConnection.getOutputStream());
wr.write(data.toString());
wr.flush();
urlConnection.connect();
reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
//read server response
while((line = reader.readLine()) != null) {
sb.append(line);
}
//receive server "answer"
try {
return getToken(sb.toString());
}catch(JSONException e) {
Log.e("LOG", "unexpected JSON exception", e);
e.printStackTrace();
} finally{
if (urlConnection != null) {
urlConnection.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (final IOException e) {
Log.e("MainActivity", "Error closing stream", e);
}
}
}
//return sb.toString();
return null;
}
catch(IOException e) {
Log.e("LoginTask", "Error ", e);
// If the code didn't successfully get the data, there's no point in attempting
// to parse it.
//forecastJsonStr = null;
return null;
}
}
public void onPostExecute(String result) {
super.onPostExecute(result);
//Log.v("RESULT", result);
if(result == null) {
CharSequence text = "no internet connection";
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(MainActivity.this, text, duration);
toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
toast.show();
}
if(loginSuccess == 0) {
// if the request wasn't successful
// give user a message via toast
CharSequence text = "wrong password or user. please try again";
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(MainActivity.this, text, duration);
toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
toast.show();
}
else {
// save token in shared preferences
SharedPreferences tokenPref = getSharedPreferences(getString(R.string.preference_token), Context.MODE_PRIVATE);
SharedPreferences.Editor editorToken = tokenPref.edit();
editorToken.putString(getString(R.string.saved_auth_token), result);
editorToken.commit();
//save login status = 1 in shared preferences
SharedPreferences loginPref = getSharedPreferences(getString(R.string.preference_logged_in), Context.MODE_PRIVATE);
SharedPreferences.Editor editorLogin = loginPref.edit();
editorLogin.putString(getString(R.string.saved_login), "1");
editorLogin.commit();
Intent mapsIntent = new Intent(getApplicationContext(), MapsActivity.class);
startActivity(mapsIntent);
}
}
}
I am using the following code to request a response from a webserver. The server sends a malformed response without headers which causes a ClientProtocolException. I have tried to use inspectors but they are not called before the exception is fired. I cannot change the server (it is within an embedded device, ALFA router R36).
Any suggestions to deal with this problem (btw: the code works perfect if the server response is well-formed)
Thanks in advance, Ton
class httpRequestTask extends AsyncTask <Integer, Integer, Integer> {
StringBuffer respTxt = new StringBuffer("");
int reqCode = 0;
protected Integer doInBackground(Integer... requestCode) {
Integer reqStatus = 0;
String url = "http://192.168.2.1/";
String authString = ("admin:admin");
switch( reqCode = requestCode[0].intValue()){
case Constants.HTTP_GET_STATUS_INFO: url += "/adm/status_info.asp"; break;
case Constants.HTTP_SCAN: url += "/goform/getUsbStaBSSIDListForm"; break;
}
try {
DefaultHttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet();
HttpResponse response;
request.setURI( new URI( url));
request.addHeader("Authorization", "Basic " + Base64.encodeToString(authString.getBytes(),Base64.NO_WRAP));
response = client.execute(request);
reqStatus = response.getStatusLine().getStatusCode();
String line;
BufferedReader in = new BufferedReader( new InputStreamReader(response.getEntity().getContent()));
while((line = in.readLine()) != null) respTxt.append(line);
} catch ( ClientProtocolException e){
Log.e("ALFA", "HTTPReq:ClientProtocolException " + e.toString());
} catch ( IOException e){
Log.e("ALFA", "HTTPReq:IOException " + e.toString());
} catch ( Exception e){
Log.e("ALFA", "HTTPReq:Exception " + e.toString());
}
return reqStatus;
}
protected void onPostExecute(Integer reqStatus) {
Intent intent = new Intent(Constants.HTTP_RESPONSE);
intent.putExtra( "reqCode", reqCode);
intent.putExtra( "reqStatus", reqStatus);
intent.putExtra( "rspTxt", respTxt.toString());
getBaseContext().sendBroadcast(intent);
}
}
Looking further to find a solution to the problem I found a suggestion to use a socket to request the server. I used Fiddler in combination with a browser on my PC to examine the data send to and received from the buggy server and read an article on Wikipedia, explaining the HTTP protocol. With that info and by using a Socket, I wrote a very basic httpRequestHandler than deals with the miss formed response from the buggy web server.
class httpSocketRequest extends AsyncTask<Integer, Integer, Integer> {
StringBuffer respTxt = new StringBuffer("");
int reqCode = 0;
int reqStatus = 0;
protected Integer doInBackground(Integer... requestCode) {
String ip = "192.168.2.1";
String path = "";
String authString = ("admin:admin");
Socket socket = null;
switch( reqCode = requestCode[0].intValue()){
case Constants.HTTP_GET_STATUS_INFO: path = "adm/status_info.asp"; break;
case Constants.HTTP_SCAN: path = "goform/getUsbStaBSSIDListForm"; break;
}
try {
socket = new Socket( ip, 80);
PrintWriter out = new PrintWriter( socket.getOutputStream());
out.println( "GET http://" + ip + "/" + path + " HTTP/1.0");
out.println( "Authorization: Basic " + Base64.encodeToString(authString.getBytes(),Base64.NO_WRAP));
out.println( "");
out.flush();
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String line;
int lineCnt = 0;
while((line = in.readLine()) != null){
if( lineCnt >= 0){
lineCnt++;
if(lineCnt == 1){ // first line should start with "HTTP/1.x " followed by a 3 digit status
if( line.length() > 12 && line.substring(0, 6).equals("HTTP/1")){
int p = line.indexOf(" ");
reqStatus = Integer.parseInt(line.substring(p+1, p+4));
continue;
} else { // not a well formed response
lineCnt = -1; // just put everything into respTxt
reqStatus = 200; // and assume everything went OK
}
} else if( lineCnt > 1){ // process rest of headers
if( line.length() == 0){
lineCnt = -1; // done with headers
} else {
// TODO insert code to process other headers
}
continue;
}
}
respTxt.append(line + "\n");
}
} catch (Exception e) {
Log.e("ALFA", "HTTPReq:Exception " + e.toString());
} finally {
try {
if( socket != null) socket.close();
} catch (IOException e) {
Log.e("ALFA", "HTTPReq:Exception closing socket" + e.toString());
}
}
return reqStatus;
}
protected void onPostExecute(Integer reqStatus) {
Intent intent = new Intent(Constants.HTTP_RESPONSE);
intent.putExtra( "reqCode", reqCode);
intent.putExtra( "reqStatus", reqStatus);
intent.putExtra( "rspTxt", respTxt.toString());
getBaseContext().sendBroadcast(intent);
}
}
I have a method to insert data into server like this:
public void doInsert(){
try {
// setiap parameter yang akan dikirim melalui http
// harus encode agar
// dapat terbaca dengan baik oleh server
String no_imei = URLEncoder.encode(noImei.getText().toString(), "utf-8");
String nik = URLEncoder.encode(user.getText().toString(), "utf-8");
String pass = URLEncoder.encode(password.getText().toString(), "utf-8");
url += "?no_imei=" + no_imei + "&&nik=" + nik + "&&password=" + pass;
getRequest(url);
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Another method that I have:
public void getRequest(String Url) {
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(url);
try {
HttpResponse response = client.execute(request);
Toast.makeText(this, "Tambah Data " + request(response) + " ",Toast.LENGTH_SHORT).show();
} catch (Exception ex) {
//Toast.makeText(this, "Tambah Data Gagal !", Toast.LENGTH_SHORT).show();
}
}
And like this:
public static String request(HttpResponse response) {
String result = "";
try {
InputStream in = response.getEntity().getContent();
BufferedReader reader = new BufferedReader(
new InputStreamReader(in));
StringBuilder str = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
str.append(line + "\n");
}
in.close();
result = str.toString();
} catch (Exception ex) {
result = "Error";
}
return result;
}
onClick method:
private View.OnClickListener onSave=new View.OnClickListener()
{
public void onClick(View v)
{
//Dbhelper helper = new Dbhelper(UserForm.this);
Cursor c = helper.Login(almagId);
if (noImei.getText().toString().equals("")||
user.getText().toString().equals("")||
password.getText().toString().equals("")
) {
Toast.makeText(UserForm.this, "Data Harus di isi", Toast.LENGTH_LONG).show();
}else if(c.moveToFirst()){
if(noImei.getText().equals(c.getString(0))||
user.getText().equals(c.getString(1))){
Toast.makeText(UserForm.this, "Data Sudah ada", Toast.LENGTH_LONG).show();
helper.close();
}
}else
{
doInsert();
helper.insertUser(noImei.getText().toString(),user.getText().toString(),password.getText().toString());
//Toast.makeText(UserForm.this, "Data Berhasil disimpan", Toast.LENGTH_LONG).show();
}
startActivity(new Intent(UserForm.this,MenuUtama.class));
user.setText("");
password.setText("");
return;
}
};
In the onClick method when response from server SUCCESS I want to do some activity. How can I do that? I tried with condition if my activity not running.
You should probably go with
if (response != null && response.getStatusLine().getStatusCode() == 200) { }
You have to add your activity in AndroidManifest.xml. Refer this link : Using Intent in an Android application to show another activity
looks like login in your if statement is little off.
if(request(response).equals("SUCCESS")){ startActivityForResult(new Intent(this,MainMenu.class))}
first, this does not make sense
if(request(response).equals("SUCCESS"))
what are you trying to do, cast request into response???
second:
.equals("SUCCESS"))
response is not an String object, are you looking for status code??
read over Android's HttpResponse
http://developer.android.com/reference/org/apache/http/HttpResponse.html
Example Code
if (response != null && response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
//Do Something
}