How to send request from android to servlet with parameters - java

I am trying to send a request from my android device to servlet with parameters and parameters are sending as part of the request.
I have a button on clicking on that I get the text from editText views modify my url to make a url with parameters and send that url to AsyncTask.
Here is my code.
buttonRegister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String stringUrl = "http://192.168.11.4:8084/WebApplication1/DemoServlet?email=" + editTextEmail.getText() + "&password=" + editTextPassword.getText() + "&phone=" + editTextPhoneNumber.getText();
ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
new RegistrationTask().execute(stringUrl);
} else {
Toast.makeText(RegisterActivity.this, "Error!. Please check your internnet connection", Toast.LENGTH_SHORT).show();
}
}
});
}
And here is my RegistrationTask code.
class RegistrationTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
return getResponse(params[0]);
}
#Override
protected void onPostExecute(String result) {
editTextEmail.setText(result);
}
public String getResponse(String myurl) {
InputStream is = null;
String contentAsString = null;
int len = 500;
try {
URL url = new URL(myurl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestMethod("GET");
conn.setDoInput(true);
conn.connect();
int response = conn.getResponseCode();
Log.d("Download", "The response is: " + response);
is = conn.getInputStream();
// Convert the InputStream into a string
contentAsString = readIt(is, len);
return contentAsString;
} catch (Exception e) {
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return contentAsString;
}
// Reads an InputStream and converts it to a String.
public String readIt(InputStream stream, int len) throws IOException, UnsupportedEncodingException {
Reader reader = null;
reader = new InputStreamReader(stream, "UTF-8");
char[] buffer = new char[len];
reader.read(buffer);
return new String(buffer);
}
}
I tried to debug my servlet code but request coming as email=password=phone=
Please help me to sort it out.

Not an answer, but would help you.
First please share the servlet code too
Second, encode parameter using URLEncoder.encode(arg:String):String before sending the request, such as following
String stringUrl = "http://192.168.11.4:8084/WebApplication1/DemoServlet?email="
+URLEncoder.encode(editTextEmail.getText())
Also your method readIt(stream:InputStream,len:int):String is not reliable because of the way yo read the info.
Note that InputStream.read(buf::byte[]):int would not fill the whole buffer even if too much data is available, and the int response indicates the number of data was written to the buffer, so your code would get data inconsistency.
You may using DataInputStream.readFully(buff:byte[]):void which either fills the buffer completely or throws exception when there are not enough data.
Or better way read till EOS, where read() method returns -1.

Related

Is there an Alternative for AsyncTask using HttpUrlConnection

Using AsyncTask freezes my whole app. i have an icon that rotates while the Http action is happening in the background. but the app just freezes till it finishes that action. Is there an alternative?
The below class sends the JSON to the server, the server has multiple endpoints and stuff like that. now when calling class calls the execute() method, the app freezes until the task is complete.
public class Connector extends AsyncTask<String, Void, Void> {
private String ip = "http://192.168.1.127";
private String port = "5000";
private URL Url;
private JSONObject jsonObject;
private String method = "";
private StringBuilder output = new StringBuilder();
Connector(String url, JSONObject jsonObject, String method)
{
try {
this.method = method;
this.Url = new URL(ip+":"+port+url);
} catch (MalformedURLException e) {
e.printStackTrace();
}
this.jsonObject = jsonObject;
//Connect to URL
}
#Override
protected Void doInBackground(String... strings) {
try {
HttpURLConnection httpURLConnection = (HttpURLConnection) Url.openConnection();
Log.i("Data", "Data sent => " + jsonObject.toString());
try {
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
httpURLConnection.setRequestMethod(method);
httpURLConnection.setRequestProperty("content-type", "application/json");
httpURLConnection.connect();
DataOutputStream outputStream = new DataOutputStream(httpURLConnection.getOutputStream());
if(jsonObject != null)
{
outputStream.writeBytes(jsonObject.toString());
outputStream.flush();
outputStream.close();
}
InputStreamReader inputStreamReader = new InputStreamReader((InputStream) httpURLConnection.getContent(), Charset.forName("UTF-8"));
BufferedReader reader = new BufferedReader(inputStreamReader);
String line = reader.readLine();
while(line != null)
{
output.append(line);
line = reader.readLine();
}
}finally {
httpURLConnection.disconnect();
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
String getMessge() {
Log.i("Data", "Data received <= " + output.toString());
return output.toString();
}
}
Please use Retrofit library.
You can find samples to use Retrofit easily.
https://www.journaldev.com/13639/retrofit-android-example-tutorial
This is one of them.
Hope it to help you. Thanks.

Async Task to Save data in SQL server in Android

I am trying to save edit box data in SQL server by using android app. I am trying to use async task to save data.I already developed web service and host in the IIS which is running fine. So i Need now code in android to save data.
This is my Aysnc Task
class SaveScan extends AsyncTask<String,Void, String>{
String status = null;
protected void onPreExecute(){
}
protected String doInBackground(String... connUrl){
HttpURLConnection conn = null;
BufferedReader reader;
try{
final URL url = new URL(connUrl[0]);
conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setChunkedStreamingMode(0);
conn.addRequestProperty("Content-Type","application/json: charset=utf-8");
conn.setRequestMethod("POST");;
JSONObject jsonObject = new JSONObject();
jsonObject.put("scans",Scan1);
OutputStream out = new BufferedOutputStream(conn.getOutputStream());
out.write(jsonObject.toString().getBytes());
out.close();
int result = conn.getResponseCode();
if (result == 200) {
InputStream in = new BufferedInputStream(conn.getInputStream());
reader = new BufferedReader(new InputStreamReader(in));
StringBuilder sb = new StringBuilder();
String line = null;
while((line =reader.readLine()) != null){
status = line;
}
}
}catch(Exception ex){
}
return status;
}
protected void onPostExecute(String result){
super.onPostExecute(result);
if(result != null){
Toast.makeText(MainActivity.this,"Scan Saved ",Toast.LENGTH_LONG).show();
}else{
Toast.makeText(MainActivity.this,"Not Saved",Toast.LENGTH_LONG).show();
}
}
}
This is Mine Button Call
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{
Manifest.permission.CAMERA},
100);
Intent intent = new Intent(MainActivity.this, Scan.class);
startActivity(intent);
}
});
private void onSaveClicked() {
new SaveScan(url).execute();
}
private class SaveScan extends AsyncTask<String,Void, String>{
String status = null;
protected String doInBackground(String... connUrl){
try {
// This is getting the url from the string we passed in
URL url = new URL(connUrl[0]);
// Create the urlConnection
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);
urlConnection.setRequestProperty("Content-Type", "application/json");
urlConnection.setRequestMethod("POST");
// OPTIONAL - Sets an authorization header
urlConnection.setRequestProperty("Authorization", "someAuthString");
JSONObject jsonObject = new JSONObject();
jsonObject.put("scans","someString");
// Send the post body
OutputStreamWriter writer = new OutputStreamWriter(urlConnection.getOutputStream());
writer.write(jsonObject.toString());
writer.flush();
int statusCode = urlConnection.getResponseCode();
if (statusCode == 200) {
InputStream inputStream = new BufferedInputStream(urlConnection.getInputStream());
String response = convertInputStreamToString(inputStream);
status=response ;
// From here you can convert the string to JSON with whatever JSON parser you like to use
} else {
// Status code is not 200
// Do something to handle the error
status=null;
}
} catch (Exception e) {
Log.d("SaveScan", e.getMessage());
}
return status;
}
private String convertInputStreamToString(InputStream inputStream) {
BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(inputStream));
StringBuilder sb = new StringBuilder();
String line;
try {
while((line = bufferedReader.readLine()) != null) {
sb.append(line);
}
} catch (IOException e) {
e.printStackTrace();
}
return sb.toString();
}
protected void onPostExecute(String result){
super.onPostExecute(result);
if(result != null){
Toast.makeText(MainActivity.this,"Scan Saved ",Toast.LENGTH_LONG).show();
}else{
Toast.makeText(MainActivity.this,"Not Saved",Toast.LENGTH_LONG).show();
}
}
}
You can choose between different storage frameworks such as Room, SQLite or Preferences depending on your data. Room and SQLite are relational databases, where SQLite requires developers to create tables and map relationships, Room takes care of those with the help of annotation processing. Preferences are android's storage framework where you can store minimal amount of data for example settings for your app, map app's flow and vital data such as user information. In the end, it all depends on the time you can spend and the data that you are trying to save. I suggest you go through all these frameworks and identify what's best for you.

progressDialoge not Updating

i have been using AsyncTask to download a certain file and went through a few tutorials and just failed to get the progress bar to move with the download. the code is and AsyncTask that calls a method to do the HTTP connection and then comes back to assort the data in a proper way to manipulate it for the app
this is my AsynTask that is on the MainActivity
private class getFood extends AsyncTask<Void, Integer, Cursor> {
private ProgressDialog mProgressDialog;
#Override
protected Cursor doInBackground(Void... params) {
// Create URL object
String site = "https://afternoon-ridge-50060.herokuapp.com/allsnacks";
URL url = createUrl(site);
// Perform HTTP request to the URL and receive a JSON response back
String jsonResponse = null;
try {
String jsonResponseEmpty = "";
// If the URL is null, then return early.
if (url == null) {
jsonResponse = jsonResponseEmpty;
}
HttpURLConnection urlConnection = null;
InputStream inputStream = null;
try {
assert url != null;
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setReadTimeout(20000 /* milliseconds */);
urlConnection.setConnectTimeout(25000 /* milliseconds */);
urlConnection.setRequestMethod("GET");
urlConnection.setRequestProperty("Authorization", "\"token\": " + token);
urlConnection.connect();
// If the request was successful (response code 200),
// then read the input stream and parse the response.
if (urlConnection.getResponseCode() == 200) {
int fileLength = urlConnection.getContentLength();
Log.d("size", String.valueOf(fileLength));
inputStream = urlConnection.getInputStream();
StringBuilder output = new StringBuilder();
if (inputStream != null) {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, Charset.forName("UTF-8"));
BufferedReader reader = new BufferedReader(inputStreamReader);
String line = reader.readLine();
jsonResponse = output.toString();
} else {
Log.e(LOG_TAG, "Error response code: " + urlConnection.getResponseCode());
}
} catch (IOException e) {
Log.e(LOG_TAG, "Problem retrieving the Food JSON results.", e);
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (inputStream != null) {
// Closing the input stream could throw an IOException, which is why
// the makeHttpRequest(URL url) method signature specifies than an IOException
// could be thrown.
inputStream.close();
}
}
} catch (IOException e) {
Log.e(LOG_TAG, "Problem making the HTTP request.", e);
}
// Extract relevant fields from the JSON response and create a list of {#link Earthquake}s
//*List<FoodList> Food = extractFeatureFromJson(jsonResponse);
Cursor foodTable = extractFeatureFromJson(jsonResponse);
// Return the list of {#link Earthquake}s
Log.d("food", "done");
return foodTable;
}
#Override
protected void onProgressUpdate(Integer... values) {
// if we get here, length is known, now set indeterminate to false
mProgressDialog.setProgress(values[0]);
}
#Override
protected void onPreExecute() {
super.onPreExecute();
// Create progress dialog
mProgressDialog = new ProgressDialog(loginActivity.this);
// Set your progress dialog Title
mProgressDialog.setTitle("Downloading");
// Set your progress dialog Message
mProgressDialog.setMessage("Downloading Important Files, Please Wait!");
mProgressDialog.setIndeterminate(false);
mProgressDialog.setMax(100);
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
// Show progress dialog
mProgressDialog.show();
}
#Override
protected void onPostExecute(Cursor data) {
try {
int foodNumberColIndex = data.getColumnIndex(COLUMN_NDB_NO);
int foodNameColIndex = data.getColumnIndex(COLUMN_NAME);
int waterColIndex = data.getColumnIndex(COLUMN_WATER_G);
int energyColIndex = data.getColumnIndex(COLUMN_ENERGY_KCAL);
int proteinColIndex = data.getColumnIndex(COLUMN_PROTEIN_G);
int lipidColIndex = data.getColumnIndex(COLUMN_LIPID_TOT_G);
int ashColIndex = data.getColumnIndex(COLUMN_ASH_G);
int carboColIndex = data.getColumnIndex(COLUMN_CARBOHYDRT_G);
while (data.moveToNext()) {
Log.d("in", " progress");
FoodList foodItem = new FoodList(data.getInt(foodNumberColIndex),
data.getString(foodNameColIndex).trim().replace(",", "."),
data.getDouble(waterColIndex),
data.getDouble(energyColIndex),
data.getDouble(proteinColIndex),
data.getDouble(lipidColIndex),
data.getDouble(ashColIndex),
data.getDouble(carboColIndex));
allFood.add(foodItem);
}
} finally {
data.close();
}
mProgressDialog.dismiss();
startActivity(intentNew);
}
private URL createUrl(String stringUrl) {
URL url = null;
try {
url = new URL(stringUrl);
} catch (MalformedURLException e) {
Log.e(LOG_TAG, "Problem building the URL ", e);
}
return url;
}
private Cursor extractFeatureFromJson(String foodJSON) {
// If the JSON string is empty or null, then return early.
if (TextUtils.isEmpty(foodJSON)) {
return null;
}
try {
// Create a JSONArray from the JSON response string
JSONArray foodArray = new JSONArray(foodJSON);
for (int i = 0; i < foodArray.length(); i++) {
JSONObject foodObject = foodArray.getJSONObject(i);
ContentValues values = new ContentValues();
values.put(COLUMN_NDB_NO, foodObject.optInt(COLUMN_NDB_NO));
values.put(COLUMN_NAME, foodObject.optString(COLUMN_NAME));
values.put(COLUMN_WATER_G, foodObject.optDouble(COLUMN_WATER_G));
values.put(COLUMN_ENERGY_KCAL, foodObject.optDouble(COLUMN_ENERGY_KCAL));
values.put(COLUMN_PROTEIN_G, foodObject.optDouble(COLUMN_PROTEIN_G));
values.put(COLUMN_LIPID_TOT_G, foodObject.optDouble(COLUMN_LIPID_TOT_G));
values.put(COLUMN_ASH_G, foodObject.optDouble(COLUMN_ASH_G));
values.put(COLUMN_CARBOHYDRT_G, foodObject.optDouble(COLUMN_CARBOHYDRT_G));
foodNutriProvider insert = new foodNutriProvider();
insert.insert(CONTENT_URI, values);
}
} catch (JSONException e) {
// If an error is thrown when executing any of the above statements in the "try" block,
// catch the exception here, so the app doesn't crash. Print a log message
// with the message from the exception.
Log.e("foodSearch", "Problem parsing the earthquake JSON results", e);
Log.e("foodSearch", foodJSON);
}
foodNutriProvider getTable = new foodNutriProvider();
// Return the list of earthquakes
return getTable.query(CONTENT_URI, null, null, null, null);
}
}
You have to publish the progress and then only the Integer... values has proper values.
Something like:
#Override
protected String doInBackground(Context... params) {
//Part-1 of the task done
publishProgress(20);
//Part-2 of the task done
publishProgress(50);
//Part-3 of the task done
publishProgress(100);
return “success”;
}
As per android documentation:
"onProgressUpdate(Progress...), invoked on the UI thread after a call to publishProgress(Progress...). The timing of the execution is undefined. This method is used to display any form of progress in the user interface while the background computation is still executing. For instance, it can be used to animate a progress bar or show logs in a text field"
use it

Token is showing expired when sending from android

When I'm sending a token(Bearer) from postman it is working fine. But when I'm sending the same token from the android app and it is showing token is expired but is it fresh and not expired and token is working fine with the postman.
I tried sending a get request without token and it is working fine. The server is running fine the class is working as excepted except authetication.
Node js code for checking the token:
const jwt = require('jsonwebtoken');
const JWT_KEY = require('../../config').getJwtSecrete();
module.exports = async (req, res, next) => {
try {
let token = req.headers.authorization;
token = getTokenFromHeader(token);
const decoded = jwt.verify(token, JWT_KEY);
req.email = decoded.email;
next();
} catch (error) {
return res.status(401).json({
message: 'Auth failed'
});
}
};
function getTokenFromHeader(token) {
return token.split(" ")[1];
}
Android: My get request method for sending the request
public class GET_Request extends AsyncTask<String, Void, Bundle> {
private static final String REQUEST_METHOD = "GET";
private static final int READ_TIMEOUT = 10000;
private static final int CONNECTION_TIMEOUT = 10000;
private GETAsyncResponse delegate;
public GET_Request(GETAsyncResponse delegate) {
this.delegate = delegate;
}
#Override
protected Bundle doInBackground(String... params) {
String Url = params[0];
Bundle bundle = new Bundle();
String result = null;
BufferedInputStream bufferedInputStream;
ByteArrayOutputStream byteArrayOutputStream;
try {
URL requestUrl = new URL(Url);
HttpURLConnection connection = (HttpURLConnection) requestUrl.openConnection();
connection.setRequestMethod(REQUEST_METHOD);
connection.setReadTimeout(READ_TIMEOUT);
connection.setConnectTimeout(CONNECTION_TIMEOUT);
connection.setDoInput(true);
connection.setUseCaches(false);
connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
connection.setRequestProperty("Accept", "application/json");
connection.setRequestProperty("Authorization", "Bearer " + UserInfo.getToken());
connection.connect();
if (connection.getResponseCode() == HTTP_OK) {
bufferedInputStream = new BufferedInputStream(connection.getInputStream());
int bisReadResult = bufferedInputStream.read();
byteArrayOutputStream = new ByteArrayOutputStream();
while (bisReadResult != -1) {
byteArrayOutputStream.write((byte) bisReadResult);
bisReadResult = bufferedInputStream.read();
}
result = byteArrayOutputStream.toString();
} else { //reading error
Log.e("doInBackground: ", String.valueOf(connection.getResponseCode()));
String error;
bufferedInputStream = new BufferedInputStream(connection.getInputStream());
int bisRealError = bufferedInputStream.read();
byteArrayOutputStream = new ByteArrayOutputStream();
while (bisRealError != -1) {
byteArrayOutputStream.write((byte) bisRealError);
bisRealError = bufferedInputStream.read();
}
/*This error string is for debugging*/
error = byteArrayOutputStream.toString();
Log.e("Error Buffer: ", error);
}
bundle.putString(JSON, result);
bundle.putInt(RESPONSE_CODE, connection.getResponseCode());
connection.disconnect();
} catch (FileNotFoundException f) {
f.printStackTrace();
bundle.putInt(RESPONSE_CODE, 400);
}
/*Internet not connected*/ catch (SocketTimeoutException s) {
bundle.putInt(RESPONSE_CODE, 0);
}
/*Any other error*/ catch (IOException e) {
e.printStackTrace();
bundle.putInt(RESPONSE_CODE, 500);
}
return bundle;
}
protected void onPostExecute(Bundle result) {
super.onPostExecute(result);
delegate.AfterGetRequestFinish(result);
}
public interface GETAsyncResponse {
void AfterGetRequestFinish(Bundle bundle);
}
}
I want it to authenticate successfully. But I don't know why it is failing and showing code '401' and 'java.io.FileNotFoundException'.
One of the features of JWT is that they are essentially tamper-proof. That is, assuming your suspect JWT has a valid signature and checksum on the Node JS server side, then it means that your Android Java code could not possibly have altered the expiration date of that token.
That being said, the most likely explanation here is that the token you are passing in fact has already expired. This could come about for a number of reasons, most likely that you have cached an old token somewhere, perhaps in shared preferences.

How to access HttpResponse returned by HttpURLConnection InputStream in Android?

I have adopted the code in this Stack Overflow answer to successfully POST JSON from my Android app to a Python/Django server. Here is my (very close) adaptation of the POST code:
// In my activity's onCreate method
try {
JSONObject obj = new JSONObject(strJSON);
new postJSON().execute("https://www.placeholder.com/generate_json", obj.toString());
} catch (Throwable t) {
Log.e("JSON Error", "Could not parse malformed JSON: " + strJSON);
}
// Outside onCreate
private class postJSON extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
String data = "";
HttpURLConnection httpURLConnection = null;
try {
httpURLConnection = (HttpURLConnection) new URL(params[0]).openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(httpURLConnection.getOutputStream());
wr.writeBytes("PostData=" + params[1]);
wr.flush();
wr.close();
InputStream in = httpURLConnection.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(in);
int inputStreamData = inputStreamReader.read();
while (inputStreamData != -1) {
char current = (char) inputStreamData;
inputStreamData = inputStreamReader.read();
data += current;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (httpURLConnection != null) {
httpURLConnection.disconnect();
}
}
return data;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
Log.e("TAG", result);
}
}
I now want to access the HttpResponse returned by the server, which I think is contained in data (but I'm not sure about this). If data does contain the HttpResponse, I would like to print it in a Toast.
Does data already contain the HttpResponse from the server or do I need to take additional steps to get it from InputStream? If it is already there, where should I put my Toast.makeText code to print the HttpResponse (i.e. data) in a Toast?
The variable data is a String containing the response body from the server and will be available to you on your UI thread as the variable result in the method onPostExecute
There are many patterns for getting the result from an async task. Here is one simple way to do it, try this approach to get a toast.
Write your execution of the task as such:
// In your activity's onCreate method
try {
JSONObject obj = new JSONObject(strJSON);
new postJSON() {
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
Toast.makeText(getApplicationContext(), result, Toast.LENGTH_LONG).show();
}
}.execute("https://www.placeholder.com/generate_json", obj.toString());
} catch (Throwable t) {
Log.e("JSON Error", "Could not parse malformed JSON: " + strJSON);
}

Categories

Resources