HTTPEntity Giving a null value - java

I have a forgot password page on my Android app. If I enter in no email it returns the correct response from the server, and if I enter in an email that is found in our database then it sends the user an email and returns the correct response from the server. However if I enter in an email and it is not found in our database, when I call
HttpEntity entity = response.getEntity();
entity is a null value. I'm not sure why it would work for 2 of the cases but not the third.
Does anyone know why that would be? My code is as follows
Android Code:
private void accessURL(String url) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
if (url.equalsIgnoreCase(Global.forgotPasswordURL)) {
InputStream is = null;
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("email", email.getText().toString()));
try {
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
if(entity != null){
is = entity.getContent();
String jsonResult = inputStreamToString(is).toString();
if (jsonResult.equalsIgnoreCase("Please enter your Email")) {
new AlertDialog.Builder(this).setTitle("Please Enter Your Email Address")
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// continue with delete
}
}).show();
}else if(jsonResult.equalsIgnoreCase("Email Address Not Found")){
new AlertDialog.Builder(this).setTitle("The Email Address You Entered has not Been Found").setMessage("Make sure that you entered your email correctly.")
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
}).show();
}else{
new AlertDialog.Builder(this).setTitle("Your Email Has Been Found!").setMessage("Check the email you provied for further instructions on resetting your password.")
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
}).show();
}
}else{
Log.d("Null", "null");
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
PHP Code:
if (isset($_POST["email"]) && !empty($_POST['email'])) {
$con=mysqli_connect("localhost","***********","******","*******");
$email = $_POST['email'];
$query = mysql_query("SELECT * FROM users WHERE email = '$email'");
$query2 = mysql_query("SELECT * FROM tempusers WHERE email = '$email'");
$ans = mysql_num_rows($query);
$ans2 = mysql_num_rows($query2);
$str = $ans . " " . $ans2;
if(mysql_num_rows($query) == 0 && mysql_num_rows($query2) == 0){
sendResponse(205, "Email Address Not Found");
return false;
}
$temp = false;
if(mysql_num_rows($query2) != 0){
$temp = true;
$query1 = mysql_query("SELECT * FROM tempusers WHERE email = '$email'");
$row = mysql_fetch_array($query1);
mailUser($email, $row['firstname'], $temp);
sendResponse(200, "Email Address Found".$str);
return true;
}else{
$query1 = mysql_query("SELECT * FROM users WHERE email = '$email'");
$row = mysql_fetch_array($query1);
mailUser($email, $row['firstname'], $temp);
sendResponse(200, "Email Address Found".$str);
return true;
}
}
sendResponse(400, 'Please enter your Email');
return false;
Any help fixing this would be greatly appreciated, thanks!

As far as I understand it behaves according to specification of HttpEntity for 205 responses. Here is what the spec says:
HTTP messages can carry a content entity associated with the request
or response. Entities can be found in some requests and in some
responses, as they are optional. Requests that use entities are
referred to as entity enclosing requests. The HTTP specification
defines two entity enclosing request methods: POST and PUT. Responses
are usually expected to enclose a content entity. There are exceptions
to this rule such as responses to HEAD method and 204 No Content, 304
Not Modified, 205 Reset Content responses.
In case if email was not found you can send 404 response code in PHP and check in your Java code:
if(response.getStatusLine().getStatusCode() == 404){
//email was not found
}

send same 200 code for email not found as well
sendResponse(200, "Email Address Not Found");

Related

Java/Wordpress REST API - Keep user authenticated?

I'm using the below code on my main activity to log the user into my app. The app's backend is Wordpress. The server returns a success message, and the user is authenticated, but as soon as I get to the next screen/activity, and attempt to have the user create a post to wordpress, the server returns the message
"Sorry, you are not allowed to create posts as this user."
Especially odd in this case because the user credentials I'm using to login are the admin user.
Any idea how I can fix this?
LoginActivity (my user logs in successfully):
private class UserNetwork extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... voids) {
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("username", "admin");
jsonObject.put("password", "123456");
} catch (JSONException e) {
e.printStackTrace();
}
OkHttpClient client = new OkHttpClient();
MediaType JSON = MediaType.parse("application/json; charset=utf-8");
RequestBody body = RequestBody.create(JSON, jsonObject.toString());
Request request = new Request.Builder()
.url("http://myurl.com/wp-json/wp/v2/custom-plugin/login")
.post(body)
.build();
Response response = null;
try {
response = client.newCall(request).execute();
String resStr = response.body().string();
Log.i("The response is", String.valueOf(response));
int responseCode = response.code();
Log.i("Check response code", String.valueOf(responseCode));
if (responseCode == 200) {
Log.i("We're logged in!", String.valueOf(responseCode));
Intent i = new Intent(LoginActivity.this, DashboardActivity.class);
startActivity(i);
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
DashboardActivity (user attempts to create post, and 'Unauthorized' messsage is returned):
private class UserPosts extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... voids) {
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("title", "Our first post");
jsonObject.put("content", "this is a test");
jsonObject.put("status", "publish");
} catch (JSONException e) {
e.printStackTrace();
}
OkHttpClient client = new OkHttpClient();
MediaType JSON = MediaType.parse("application/json; charset=utf-8");
// put your json here
RequestBody body = RequestBody.create(JSON, jsonObject.toString());
Request request = new Request.Builder()
.url("http://myurl.com/wp-json/wp/v2/posts")
.post(body)
.build();
Response response = null;
try {
response = client.newCall(request).execute();
String resStr = response.body().string();
Log.i("The response is", String.valueOf(response));
int responseCode = response.code();
Log.i("Check response code", String.valueOf(responseCode));
if (responseCode == 200) {
Log.i("Creating post!", String.valueOf(responseCode));
} else {
Log.i("Post not created.", String.valueOf(responseCode));
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
The problem you're having is caused by HTTP protocol being stateless.
That means whenever you perform request, server treats you as a new entity.
In case of most authenticated requests, the client is responsible for storing the tokens issued by the server during the login, and then passing them to following requests.
When you are using the browser it is the client and usually is being responsible for handling this state (it ma also be a JavaScript code running in the browser).
In your code that is your responsibility to store this state.
While you're using OkHttp, you could use CookieJar and it would probably work. However in the end using user credentials to authenticate application is not the best idea and using extension that would allow you to specify credentials for an application as #faozi suggested would probably be a better solution.
You need to install and activate the Application Passwords plugin and then follow the instructions given
here.
But you don’t need to actually set up any Application Passwords for your users.
you need to authenticate it first : here
you can add code in WordPress file to authenticate it

Accessing a login api using http get method in android

I am developing an android app which uses a login api, which will allow its web users to login with their same credentials on the android device.....
the url for the api is
https://api.ecoachsolutions.com/main.php?ecoachsignin=1&server=remote&user=ecoachguest&pass=ecoachguest
which retuns a response in json
JSON object: {
status: <success or error>,
msg: <response message>,
profile: <user profile object>
}
I tried this code which I found searching on the internet but it isn't working,
private void doLogin(View view) {
//ALERT MESSAGE
_spinner.setVisibility(View.VISIBLE);
Toast.makeText(mContext, "connecting to server.... ",
Toast.LENGTH_SHORT).show();
// URLEncode user defined data
String usernameValue = username.getText().toString();
String passValue = password.getText().toString();
// Create http cliient object to send request to server
HttpClient Client = new DefaultHttpClient();
// Create URL string
String URL = "https://api.ecoachsolutions.com/main.php?ecoachsignin=1&server=remote&user="+usernameValue+"&pass="+passValue;
Log.i("httpget", URL);
try
{
String SetServerString ;
// Create Request to server and get response
HttpGet httpget = new HttpGet(URL);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
SetServerString = Client.execute(httpget, responseHandler);
System.out.println(usernameValue);
System.out.println(passValue);
// Show response on activity
Toast.makeText(getBaseContext(),SetServerString,Toast.LENGTH_LONG).show();
}
catch(Exception ex)
{
Toast.makeText(getBaseContext(),"Fail",Toast.LENGTH_LONG).show();
_spinner.setVisibility(View.INVISIBLE);
}
}
will appreciate the help or the positive direction thanks :)
Change your code to get the HttpResponse like below,
String responseBody = "";
HttpResponse response = client.execute(post);
int responseCode = response.getStatusLine().getStatusCode();
Log.i("GET Response Code ",responseCode + "");
switch(responseCode) {
// Means server is responding
case 200:
HttpEntity entity = response.getEntity();
if(entity != null) {
responseBody = EntityUtils.toString(entity);
// Now you can try printing your returned string here, before you go for JSON parsing
}
break;
// Add more case statements to handle other scenarios
}
The code is simple, but if still unable to understand, don't hesitate to ask.

Sending sign up data from user to server

EDIT:
I finally figured out where the problem is. I keep getting an IOException on this line
response = httpClient.execute(httpPost).
However, the normal problems that will cause this error (the ones that I searched online, like the url being wrong and such) are not the problem here. The url is correct. Can anyone help or list all of the possible reasons I would get this error. Thank you.
I know this question has been asked several times, and I actually looked at the answers given for those questions in order to originally figure out how to do this but for some reason it's not working and I don't know why.
I have an app that requires a user to sign up. After they sign up I send the information they inputted to the server.
Android code:
//This is the method called when user presses submit button. The variables not declared
//are global
public void registerUser(View v){
context = getApplicationContext();
username = ((EditText) this.findViewById(R.id.username)).getText().toString();
email = ((EditText) this.findViewById(R.id.email)).getText().toString();
password=((EditText)this.findViewById(R.id.password)).getText().toString();
String[] params = {username,email,password};
(new SendRegisterInfo(this.getApplicationContext())).execute(params);
Toast t = Toast.makeText(context, "Thank you for Signing up "+username, Toast.LENGTH_SHORT);
t.show();
//Start Main Page Activity. Page they'll see everytime they login
Intent i = new Intent(this,HomeActivity.class);
startActivity(i);
}
public class SendRegisterInfo extends AsyncTask<String,Void,Void>{
private String tag = "SendRegisterInfo";
private InputStream is;
private Context c;
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
}
public SendRegisterInfo(Context c){
this.c = c;
}
#Override
protected Void doInBackground(String... params) {
String URI="http://www.mysite.com/registerUser.php";
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(URI);
HttpResponse response;
String username,email,password;
username = params[0];
email = params[1];
password = params[2];
try {
ArrayList<NameValuePair> submit = new ArrayList<NameValuePair>(2);
submit.add(new BasicNameValuePair("username",username));
submit.add(new BasicNameValuePair("email",email));
submit.add(new BasicNameValuePair("password",password));
httpPost.setEntity(new UrlEncodedFormEntity(submit));
response = httpClient.execute(httpPost);
Log.i(tag,response.getStatusLine().toString());
} catch (ClientProtocolException e) {
Log.e(tag, "Error in http connection "+e.toString());
e.printStackTrace();
} catch (IOException e) {
Log.e(tag, "Error in http connection "+e.toString());
e.printStackTrace();
}catch (Exception e){
Log.e(tag, "Error in http connection "+e.toString());
e.printStackTrace();
}
return null;
}
}
Manifest File:
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
PHP Code:
<?php
$username = $_POST["username"];
$email = $_POST["email"];
$pswrd = $_POST["password"];
$score = 0;
$user = "root";
$password="pword";
$database = "databasename";
mysql_connect(localhost,$user,$password);
mysql_select_db($database) or die("Unable to Select Database");
$query="INSERT INTO Players VALUES ('','$username','$email','$pswrd','','$score')";
mysql_query($query);
mysql_close();
?>
You have an error reading the (String... params) argument of the doInBackground() method.
When you start the AsyncTask:
String[] params = {username,email,password};
When you read the arguments
String username,email,weight,password;
username = params[0];
email = params[1];
password = params[3]; // should be: password = params[2];
If this isn't works, adds a mySql query asking for the last insert id on the php program and print the result to get the response in the client:
response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
Log.i(tag,EntityUtils.toString(entity).toString());
So you can see if you are inserting or not on the db.
This is your issue:
RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
You're attempting to show a Toast from a class that isn't designed to show a Toast. Or, perhaps, isn't prepared to show a tost. What is the class containing the method registerUser
Please check the code below.
Add function name and key to the request along with your data.
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(3);
nameValuePairs.add((NameValuePair) new BasicNameValuePair("f", "yourFunctionName."+methodName));
nameValuePairs.add((NameValuePair) new BasicNameValuePair("u", "a0ff8a6a0a831ec25cf4de6c730be54c"));
//u is the key used by server to identify valid request.

receiving JSON response (android)

I am trying to send a JSON with the information email address, first and last names and expecting a response from the server to say {status: "Created"} or {status: "Resend"} and depending on the answer there would be a pop up message. I was wondering what I use to extract the information from the status class. Thanks!
Here is my code to accept
protected void sendJson(final String email, final String firstN,
final String lastN) {
Thread t = new Thread() {
public void run() {
Looper.prepare(); // For Preparing Message Pool for the child
// Thread
HttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(),
10000); // Timeout Limit
HttpResponse response;
JSONObject json = new JSONObject();
try {
// post in the url
HttpPost post = new HttpPost(
"https://iphone-radar.com/accounts");
json.put("email_address", email);
json.put("first_name", firstN);
json.put("last_name", lastN);
StringEntity se = new StringEntity("JSON: "
+ json.toString());
se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,
"application/json"));
post.setEntity(se);
response = client.execute(post);
/* Checking response */
if (response != null) {
String str = response.getEntity().toString();
if (str.equals("Created")) {
new AlertDialog.Builder(CreateAccount.this)
.setTitle("Account Creation Successful")
.setMessage(
"An activation code has been sent to you. Please check your SPAM folder if you do not receive your activation code email")
.setNeutralButton("OK", null).show();
} else if(str.equals("Resend")) {
new AlertDialog.Builder(CreateAccount.this)
.setTitle("Code Resent")
.setMessage(
"Your activation code has been resent to your email.\n\nIf you are not receiving your activation code, our email is being blocked. Please email us at 'help#iphone-tracker.net' and we will manually send you a code.")
.setNeutralButton("OK", null).show();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
You should convert the response to a string, then create a JSONObject. You can then just access the JSON object's properties. Try this:
org.json.JSONObject obj = new org.json.JSONObject(org.apache.http.util.EntityUtils.toString(response.getEntity()));
if ("Created".equals(obj.getString("status"))) {
new AlertDialog.Builder(CreateAccount.this)
.setTitle("Account Creation Successful")
.setMessage(
"An activation code has been sent to you. Please check your SPAM folder if you do not receive your activation code email")
.setNeutralButton("OK", null).show();
} else if("Resend".equals(obj.getString("status"))) {
new AlertDialog.Builder(CreateAccount.this)
.setTitle("Code Resent")
.setMessage(
"Your activation code has been resent to your email.\n\nIf you are not receiving your activation code, our email is being blocked. Please email us at 'help#iphone-tracker.net' and we will manually send you a code.")
.setNeutralButton("OK", null).show();
}

Open WebView with result from Http post

I having an issue from my HTTP Post.
The code I'm using are working (have tested to post data to a guestbook form and it worked).
Now what I want. I have created two EditText forms, that holds values. I have a submit button there I post this data (like the test I wrote about before), but now I want to post it into a login.php page (that in a normal browser redirects me to the member.php page).
Although I know the forms are correctly filled in and it successfully posted on the "test" site, I wanna get the response from login.php and check if the user is successfully logged in or if it failed, if succeeded -> redirect me to member.php page.
All I know is this:
HttpResponse response = httpclient.execute(httppost);
that executes the command. But how should I achieve the login check? Any further use of the response variable?
Well... your approach is not good at all. If you are going to allow user authenticate through your app, why do you want to redirect the user to a member.php page? why don't you just put the login form in a login.php file on the server and make the user browse through your site?
As user, if an app allows me to authenticate using EditTexts inside UI, I would expect to access all the content through the app instead of being redirected to a web interface.
Anyway, if you decide to continue doing it that way keep in mind that you would have to parse and process cookies manually, and inject them into the WebView (Google about the CookieManager class). That's the way how the user will really be logged-in in your web app.
Can you provide a small example of how to set it up? The stream I will get, is that a special server response for example, a successfully login?
Here you have:
public String getPostRequest(String url, String user, String pass) {
HttpClient postClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse response;
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("user", user));
nameValuePairs.add(new BasicNameValuePair("pass", pass));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
response = postClient.execute(httpPost);
if(response.getStatusLine().getStatusCode() == 200) {
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
String result = convertStreamToString(instream);
instream.close();
return result; // here is a string of the result!!!
}
}
} catch (Exception e) {}
return null; // if it gets here, something wrong happens with the connection
}
private String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
How do you use it? Something like this:
String result = getPostRequest("http://yourpage.com/login.php", "the username", "his/her pass");
if( result.equals("OK") ){
// voila!
}
I'm here supposing that you have something like this in your PHP code:
<?php
// login logic here
if( $success ){
die("OK");
}
?>

Categories