Supporting Sessions Without Cookies in Tomcat #duplicate - java

I have an Web Application with Spring Security Framework and running on Tomcat 8. Now, I am facing a new problem to create android app which support user sessions without cookies. I tried to find some documentation like this and i tried it with using HttpUrlConnection ( I don't know which one is more better with other ), this is my failure code.
public static String jsessionid = SessionIdentifierGenerator.nextSessionId();
public static String performPostCall(String requestURL,
HashMap<String, String> postDataParams) {
Log.d("url = ",requestURL);
URL url;
String response = "";
try {
url = new URL(requestURL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(45000);
conn.setConnectTimeout(45000);
conn.setRequestMethod("POST");
Log.d("Cookie : ", jsessionid);
conn.setRequestProperty("Cookie","JSESSIONID=" + SessionIdentifierGenerator.nextSessionId());
conn.setDoInput(true);
conn.setDoOutput(true);
// conn.connect();
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(getPostDataString(postDataParams));
writer.flush();
int responseCode=conn.getResponseCode();
writer.close();
os.close();
System.out.println(".toString() = "+responseCode);
System.out.println(".HttpsURLConnection.HTTP_OK = "+HttpsURLConnection.HTTP_OK);
if (responseCode == HttpsURLConnection.HTTP_OK) {
String line;
BufferedReader br=new BufferedReader(new InputStreamReader(conn.getInputStream()));
while ((line=br.readLine()) != null) {
response+=line;
}
}
else {
response="";
}
} catch (Exception e) {
e.printStackTrace();
}
return response;
}
private static String getPostDataString(HashMap<String, String> params) throws UnsupportedEncodingException{
StringBuilder result = new StringBuilder();
boolean first = true;
for(Map.Entry<String, String> entry : params.entrySet()){
Log.d("entry.getKey() = ",entry.getKey());
Log.d("entry.getValue() = ",entry.getValue());
if (first)
first = false;
else
result.append("&");
result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
}
System.out.println("tetstes = "+result.toString());
return result.toString();
}
this methode for create a new session.
public final class SessionIdentifierGenerator {
private static SecureRandom random = new SecureRandom();
public static String nextSessionId() {
return new BigInteger(130, random).toString(32);
}
}
HashMap<String, String> parameter = new HashMap<String, String>();
parameter.put("username", username);
parameter.put("password", password);
and the last i call this performPostCall("http://localhost:8080/login/authenticate?spring-security-redirect=/login/ajaxSuccess", parameter);

Related

How can I solve this IOException?

I am trying to get a user token from a url but I keep getting an IOException:
(W/System.err: java.io.FileNotFoundException: url)
I have tried to run the API from postman, and that seems to work. The request method is GET:
private class userlogin extends AsyncTask<String, String, String> {
#Override
public void onPreExecute() {
progressDialog = new ProgressDialog(userLogin.this);
progressDialog.setMessage("please wait.........");
progressDialog.setIndeterminate(false);
progressDialog.setCancelable(false);
progressDialog.setTitle("Logging in");
progressDialog.show();
}
#Override
public String doInBackground(String... para) {
try {
URL url = new URL(webconfigs.LOGIN_URL);
Map<String, String> params = new LinkedHashMap<>();
params.put("grant_type", "password");
params.put("username", para[0]);
params.put("password", para[1]);
utility.updateSharedPreference(userLogin.this, "Username", para[0]);
utility.updateSharedPreference(getApplicationContext(), "Password", para[1]);
//just to check if it is sored in the shared prefrence
utility.fetchFromSharedPreference(getApplicationContext(), "Username");
utility.fetchFromSharedPreference(getApplicationContext(), "Password");
Log.e(">>Username>>", para[0]);
Log.e(">>Password>>", para[1]);
StringBuilder postData = new StringBuilder();
for (Map.Entry<String, String> param : params.entrySet()) {
if (postData.length() != 0) postData.append('&');
postData.append(URLEncoder.encode(param.getKey(), "UTF-8"));
postData.append('=');
postData.append(URLEncoder.encode(String.valueOf(param.getValue()), "UTF-8"));
}
String urlparameters = postData.toString();
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(3000);
conn.setRequestMethod("GET");
conn.setRequestProperty("Content-Type", webconfigs.CONTENT_TYPE);
conn.setDoOutput(true);
//connect the url
conn.connect();
//conn.setDoOutput(true);
OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
writer.write(urlparameters);
writer.flush();
//create our buffered reader to read from the input stream reader
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder st = new StringBuilder();
//checking the status of the response code
Integer resposeCode = conn.getResponseCode();
String responsecode1 = resposeCode.toString();
Log.e("the respose code is :", responsecode1);
String line;
String result= "";
// consume the response and read it line by line as
while ((line = reader.readLine()) != null) {
st.append(line);
}
reader.close();
writer.close();
result = st.toString();
return result;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
Log.e(">>>>LOGINSERVERRESPONSE", ">>>>>" + result);
progressDialog.dismiss();
try {
JSONObject results = new JSONObject(result);
String token = results.getString("access_token");
if (token != null) {
String accessToken = results.getString("access_token");
String tokenType = results.getString("token_type");
String dateIssued = results.getString(".issued");
String expiryDate = results.getString(".expires_in");
}
} catch (Exception e) {
}
startActivity(new Intent(getApplicationContext(), drawerLayout.class));
}
}
the problem with using the asynchtask is that when the credentials that are used are wrong the problem will exist ,incase that happens,use a different user from the database

Post request on Android to .php file

I'm trying to make a POST request from my android app to a .php file but it doesn't work. It should send the scannedData value to my .php script but instead it returns "false: 500".
Does anybody know why? Since they changed that you can't use httppost anymore most of the answers on StackOverflow are outdated.
public class SendRequest extends AsyncTask<String, Void, String> {
protected void onPreExecute(){}
protected String doInBackground(String... arg0) {
try{
//Enter script URL Here
URL url = new URL("https://example.com/code.php");
JSONObject postDataParams = new JSONObject();
//int i;
//for(i=1;i<=70;i++)
// String usn = Integer.toString(i);
//Passing scanned code as parameter
postDataParams.put("sdata",scannedData);
Log.e("params",postDataParams.toString());
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(15000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(getPostDataString(postDataParams));
writer.flush();
writer.close();
os.close();
int responseCode=conn.getResponseCode();
if (responseCode == HttpsURLConnection.HTTP_OK) {
BufferedReader in=new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuffer sb = new StringBuffer("");
String line="";
while((line = in.readLine()) != null) {
sb.append(line);
break;
}
in.close();
return sb.toString();
}
else {
return new String("false : "+responseCode);
}
}
catch(Exception e){
return new String("Exception: " + e.getMessage());
}
}
#Override
protected void onPostExecute(String result) {
Toast.makeText(getApplicationContext(), result,
Toast.LENGTH_LONG).show();
}
}
public String getPostDataString(JSONObject params) throws Exception {
StringBuilder result = new StringBuilder();
boolean first = true;
Iterator<String> itr = params.keys();
while(itr.hasNext()){
String key= itr.next();
Object value = params.get(key);
if (first)
first = false;
else
result.append("&");
result.append(URLEncoder.encode(key, "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(value.toString(), "UTF-8"));
}
return result.toString();
}

How to do an update or "PUT" via json on android?

I need to update existing parameters in the database.
My screen receives values ​​in xml and it's those values ​​that I want to update in the database using the method put.
Here's my put code that does not work correctly :
public class PatchClass extends AsyncTask<Void, String, String> {
protected void onPreExecute() {
}
#Override
protected String doInBackground(Void... String) {
StringBuilder result = new StringBuilder();
// Toast.makeText(LoginActivity.this,"No começo de doInbackground....",Toast.LENGTH_LONG).show();
// int id = 1;
try {
String urlLogin = "http://192.168.1.207/api/v2/bookdemo/_table/cad_users";
URL url = new URL(urlLogin);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
JSONObject postDataParams = new JSONObject();
conn.setRequestProperty("Content-type", "application/json");
conn.setRequestProperty("Accept", "application/json");
conn.setRequestProperty("X-DreamFactory-Api-Key", "XXXXXXXXXXXXXXXX");
conn.setRequestProperty("X-DreamFactory-Session-Token", "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.XXXXXXXXXXXXXX.uVXdVTczx91z2NDGVV2quxvIEHhHUzX1hnVrNWQzoao");
conn.setRequestProperty("Authorization", "Basic dGhpYWdvLmNhbWFyZ29AZXZvbHV0aW9uaXQuY29tLmJyOmluaWNpYWwyMDE3'");
conn.setDoOutput(true);
conn.setRequestMethod("PUT");
OutputStreamWriter out = new OutputStreamWriter(
conn.getOutputStream());
out.write("resource");
conn.getInputStream();
conn.connect();
JSONObject resource = new JSONObject();
JSONArray array = new JSONArray();
array.put(postDataParams);
resource.put("resource", array);
postDataParams.put("id_user",id);
postDataParams.put("tx_name", nome);
postDataParams.put("tx_nickname", nickname);
postDataParams.put("password", password);
postDataParams.put("nu_cellphone", numcel);
postDataParams.put("tx_email", email);
Log.e("resource", postDataParams.toString());
System.out.println("After this Connection");
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
//writer.write(getPostDataString(postDataParams));
writer.write(resource.toString());
writer.flush();
writer.close();
os.close();
System.out.println("After this writers");
int responseCode = conn.getResponseCode();
if (responseCode == HttpsURLConnection.HTTP_OK) {
System.out.println("Funcionou!!");
Intent intent = new Intent(ActivityAttCad.this, MainActivity2.class);
startActivity(intent);
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuffer sb = new StringBuffer("");
String line = "";
while ((line = in.readLine()) != null) {
sb.append(line);
break;
}
in.close();
return sb.toString();
} else {
return new String("false : " + responseCode);
}
} catch (Exception e) {
return new String("Exception: " + e.getMessage());
}

method in class cannot be applied to given types; required: HashMap<String,Integer>

I'm doing this program and I got this error:
Error:(93, 34) error: method getPostDataString in class MainActivity.DownloadTask cannot be applied to given types;
required: HashMap
found: String,int
reason: actual and formal argument lists differ in length
protected String doInBackground(Object... params) {
URL url;
String response = "";
try {
url = new URL("http://app.iseemobile.com/imenu/getDistrictRestaurants.php");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(15000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(getPostDataString("district", 1));
writer.flush();
writer.close();
os.close();
int responseCode = conn.getResponseCode();
if (responseCode == HttpsURLConnection.HTTP_OK) {
String line;
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
while ((line = br.readLine()) != null) {
response += line;
}
} else {
response = "";
}
} catch (Exception e) {
e.printStackTrace();
}
return response;
}
With the following method:
private String getPostDataString(HashMap<String, Integer> params) throws UnsupportedEncodingException{
StringBuilder result = new StringBuilder();
boolean first = true;
for(Map.Entry<String, Integer> entry:params.entrySet()){
if (first)
first = false;
else
result.append("&");
result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(String.valueOf(entry.getValue()), "UTF-8"));
}
return result.toString();
}
You should pass map as a parameter in getPostDataString method
protected String doInBackground(Object... params) {
URL url;
String response = "";
try {
url = new URL("http://app.iseemobile.com/imenu/getDistrictRestaurants.php");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(15000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
Map<String, Integer> inputMap = new HashMap<String, Integer>();
map.put("district", 1);
writer.write(getPostDataString(map);
writer.flush();
writer.close();
os.close();
int responseCode = conn.getResponseCode();
if (responseCode == HttpsURLConnection.HTTP_OK) {
String line;
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
while ((line = br.readLine()) != null) {
response += line;
}
} else {
response = "";
}
} catch (Exception e) {
e.printStackTrace();
}
return response;
}
You are passing a string and an integer while calling getPostDataString where as it expects a HashMap<String, Integer>. Java does not convert a string and integer to a map directly. You need to create a map in calling function and send it.
Replace the following statement
writer.write(getPostDataString("district", 1));
with
Map<String, Integer> m = new HashMap<String, Integer>();
m.put("district",1);
writer.write(getPostDataString(m));

Android reads different data in JsonArray on receiving from server

I'm working on an API and I am experiencing a strange thing. When I make an API request from which I receive a JSON response. In the browser I receive the following JSON:
[
{
"SalesAgentPhone":"829698539",
"DriverStatus":"CustomerRescheduled",
"DriverStatusDescription":[
{
"Reason":"sfdfsdf",
"Date":"2016-10-02",
"SlotId":"1"
}
]
}]
But I receive a different JSON response on my Android device.
[
{
"SalesAgentPhone":"829698539",
"DriverStatus":"CustomerRescheduled",
"DriverStatusDescription":[
{"Reason":"sfdfsdf","Date":"2016-10-02","SlotId":"1"
}
]
}]
This is the class I'm using to make that Request
public class NewPost extends AsyncTask<String, Integer, String> {
private final Context context;
private final Registerinterface inter;
private int response_code = 0;
private HashMap<String, String> postDataParams;
private ProgressDialog prgDialog;
public NewPost(Context c, Registerinterface inter, HashMap<String, String> postParamater) {
context = c;
this.inter = inter;
this.postDataParams = postParamater;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
if (!new NetworkStatus(context).isNetworkAvailable()) {
inter.Result("", Constants.No_Internet);
this.cancel(true);
} else {
prgDialog = new ProgressDialog(new ContextThemeWrapper(context, android.R.style.Theme_DeviceDefault_Light_Dialog));
prgDialog.setMessage("Loading...");
prgDialog.show();
prgDialog.setIndeterminate(false);
}
}
#Override
protected String doInBackground(String... param) {
URL url;
String response = "";
try {
url = new URL(param[0]);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(15000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("GET");
conn.setDoInput(true);
conn.setDoOutput(true);
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(getPostDataString(postDataParams));
writer.flush();
writer.close();
os.close();
int responseCode = conn.getResponseCode();
if (responseCode == HttpsURLConnection.HTTP_OK) {
String line;
StringBuilder sb = new StringBuilder();
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
while ((line = br.readLine()) != null)
sb.append(line + "\n");
response = sb.toString();
return response;
} else {
response = "";
}
} catch (Exception e) {
e.printStackTrace();
}
return response;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
prgDialog.dismiss();
if (result == null || result.equals("null"))
inter.Result("null", response_code);
else
inter.Result(result, response_code);
}
private String getPostDataString(HashMap<String, String> params) throws UnsupportedEncodingException {
StringBuilder result = new StringBuilder();
boolean first = true;
for (Map.Entry<String, String> entry : params.entrySet()) {
if (first)
first = false;
else
result.append("&");
result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
}
return result.toString();
}
}
I've been stuck on this problem for hours, any help would be appreciated.
You can remove the from your JSON data.
JSON.parse(data.replace(/"/g,'"'));
You might want to fix your JSON-writing script though, because " is not valid in a JSON object.

Categories

Resources