receiving JSON response (android) - java

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();
}

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

How to send HTTP request from android app to Heroku

I have a android app that uses the twilio sdk and is hosted by heroku server. I'm trying to push a button in my app to send a HTTP request to heroku to send a REST API request to Twilio to update my twiml URL. The current way i'm trying to send the the HTTP request is not working. I have looked through all of the examples that i could find and none of them show how to do this function. Does anybody know how to do this? Thanks in advance.
This is my code for trying to send the HTTP request to heroku
holdButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://yourappnamehere.herokuapp.com/hello");
try {
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
HttpEntity ht = response.getEntity();
BufferedHttpEntity buf = new BufferedHttpEntity(ht);
InputStream is = buf.getContent();
BufferedReader r = new BufferedReader(new InputStreamReader(is));
StringBuilder total = new StringBuilder();
String line;
while ((line = r.readLine()) != null) {
total.append(line);
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//setting a toast to see if this is being initiated
Toast.makeText(getBaseContext(), "why wont it work!", Toast.LENGTH_SHORT).show();
}
;
});
This is my updated code including the volley library
holdButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//setting up a request queue from Volley API
//RequestQueue mRequestQueue;
// Instantiate the cache
Cache cache = new DiskBasedCache(getCacheDir(), 1024 * 1024); // 1MB cap
// Set up the network to use HttpURLConnection as the HTTP client.
Network network = new BasicNetwork(new HurlStack());
// Instantiate the RequestQueue with the cache and network.
mRequestQueue = new RequestQueue(cache, network);
// Start the queue
mRequestQueue.start();
String url = "http://yourappnamehere.herokuapp.com/hello";
// Formulate the request and handle the response.
StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
// Do something with the response
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// Handle error
}
});
// Add the request to the RequestQueue.
mRequestQueue.add(stringRequest);
Toast.makeText(getBaseContext(), "why wont it work!", Toast.LENGTH_SHORT).show();
}
;
});
I would suggest using a library like Google Volley which is pretty slick
https://developer.android.com/training/volley/index.html
HttpRequest is deprecated from API level 22. It would be best practice to avoid using that. Use java.net.HttpUrlConnection instead.
However, if you still want to use it, the above code needs to be run on a thread other than the UI thread as mentioned in the comment above.

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.

HTTPEntity Giving a null value

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");

Pass and receive JSON object from Jersey Resftul webservice from android

Scenario : Pass username and password in a json object to restful webservice and get a json object in return. Yeah, I know, Its simple but I can't get it work.
I have been trying to this from several days. So far, I have tried this:
My restful webservice code
#POST
#Path("/testJson")
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.APPLICATION_JSON)
public JSONObject testJson(JSONObject inputJsonObj) throws Exception {
JSONObject myjson = new JSONObject();
if(inputJsonObj != null){
System.out.println("=================================");
System.out.println("JSON object = " + inputJsonObj.toString());
System.out.println("=================================");
}
else{
System.out.println("JSON is NULL");
}
myjson.put("success", "1");
System.out.println(myjson.toString());
// return "string returned";
return myjson;
}
And inside my android acivity, the code is
// POST request to <service>/SaveVehicle
HttpPost request = new HttpPost(myURL);
request.setHeader("Accept", "application/json");
request.setHeader("Content-type", "application/json");
request.setHeader("user-agent", "Yoda");
try {
// Build JSON string
// JSONStringer vehicle = new JSONStringer().object()
// .key("getItInputTO").object().key("zipCode").value("90505")
// .key("financingOption").value("B").key("make")
// .value("Scion").key("baseAmountFinanced").value("12000")
// .key("modelYear").value("2010").key("trimCode")
// .value("6221").key("totalMSRP").value("15000")
// .key("aprRate").value("").endObject().endObject();
JSONObject myjson = new JSONObject();
myjson.put("1", "first");
myjson.put("2", "second");
StringEntity entity = new StringEntity(myjson.toString());
entity.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,"application/json; charset=utf-8"));
request.setEntity(entity);
// Send request to WCF service
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
// HttpResponse response = httpClient.execute(request, localContext);
HttpResponse response = httpClient.execute(request);
resCode = response.getStatusLine().getStatusCode();
Toast.makeText(getApplicationContext(),
response.getStatusLine().getStatusCode() + "",
Toast.LENGTH_LONG).show();
if (resCode == 200) {
Toast.makeText(getApplicationContext(),
response.getStatusLine().getStatusCode() + "",
Toast.LENGTH_LONG).show();
HttpEntity entity2 = (HttpEntity) response.getEntity().getContent();
String text = getASCIIContentFromEntity(entity);
if(text!=null){
JSONObject obj = new JSONObject(text);
lblMsg.setText("Successful!");
}
// BufferedReader in = new BufferedReader(new
// InputStreamReader(response.getEntity().getContent()));
//
//
// String line = "";
// StringBuffer returnFromServer = new StringBuffer();
//
// while ((line = in.readLine()) != null) {
// returnFromServer.append(line);
// }
// // Toast what we got from server
// Toast.makeText(getApplicationContext(),
// returnFromServer.toString(), Toast.LENGTH_LONG).show();
//
// if (entity != null) {
// entity.consumeContent();
// }
}
} catch (Exception e) {
// TODO: handle exception
}
The commented sections show previous tries.
Output that I get on server console
=================================
JSON object = {}
=================================
{"success":"1"}
My server side receiver json object is not getting populated i don't know why.
Note:
I have INTERNET and many other permissions in my android manifest.
My webservice is up and running.
I have all the required jars i.e. jersey, json etc
I am using Tomcat 7 for restful webservice
I would highly appreciate any help.
Thanks
I have the same problem as yours.
I don't know why, but the temporary solution i am using is creating a class to handle those parameters.
That means using Jackson to convert Json Object <=> "Your Class"
See this tutorial for more information:
http://www.mkyong.com/webservices/jax-rs/json-example-with-jersey-jackson/
===================================
And I just found this topic, it may be more useful than the upper solution:
Jersey POST Method is receiving null values as parameters

Categories