How to get data from MongoDB with Android AsyncHttpClient - java

Background:
I'm working on an Android project that was handed off to me and there are some things I'm still trying to learn. The people on the project before me left no documentation, so forgive me.
Question:
Basically I want to know how to get data back from our MongoDB (I think). Using AsyncHttpClient params are put sent via post
private AsyncHttpClient client = new AsyncHttpClient();
RequestParams params = new RequestParams();
params.put("authorization", getSharedPreferences("Prefs", Context.MODE_PRIVATE).getString("authToken", ""));
params.put("name", name);
params.put("email", email);
client.post(Utilities.getBaseURL() + "session/updateProfile", params, new JsonHttpResponseHandler() {
#Override
public void onSuccess(int statusCode, cz.msebera.android.httpclient.Header[] headers, JSONObject response) {
HashMap<String, String> profile = new HashMap<>();
profile.put("user_name", name);
profile.put("user_email", email);
Utilities.updateAllDetails(profile);
}
#Override
public void onFailure(int statusCode, cz.msebera.android.httpclient.Header[] headers, Throwable throwable, JSONObject response) {
Utilities.showUserDialog(context, "Profile Change Error", "Attention, there was an error in updating your profile, please try again.");
}
});
So the above code is basically updating a profile and sending the params via http post.
Later there is a get on the client:
client.get(Utilities.getBaseURL() + "session/getUserId", new JsonHttpResponseHandler() {
#Override
public void onSuccess(int statusCode, cz.msebera.android.httpclient.Header[] headers, JSONObject response) {
try {
userId = response.getString("responseString");
startActivityForResult(intent, PICK_IMAGE);
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onFailure(int statusCode, cz.msebera.android.httpclient.Header[] headers, Throwable throwable, JSONObject response) {}
});
What I don't understand is where "session/updateProfile" and "session/getUserId" come from. Is this an API call, if so how can I find what is available and also how to add to it?
Update
Found this code in a JavaScript file for the website. Maybe this can lead someone to help me put everything together?
JsonRoutes.add('get', '/api/v1/session/getUserId', function(req, res, next) {
var authToken = req.headers["authorization"];
var userObj = verifyUser(authToken);
var response = {};
if (userObj) {
response.responseString = userObj._id;
JsonRoutes.sendResult(res, 200, response);
} else {
response.responseString = "user not found";
JsonRoutes.sendResult(res, 200, response);
}
});
Do I need to add to this JS file to expand the API?

where [do] "session/updateProfile" and "session/getUserId" come from? Is this an API call
Yup, REST API call to wherever Utilities.getBaseURL() points to.
how can I find what is available?
Well, if that server is yours, then you'll need to go find some code / documentation for that. Otherwise, if it's some other external service, you'll still have to find some API documentation or contact someone who does know about it. You've mentioned in the comments that it is DigitalOcean, so it isn't an external service. There is additional server side code to inspect.
how to add to it?
If it were an external service, you probably couldn't. Since this DigitalOcean server could be running literally any service, it entirely depends on the server side programming language. You've mentioned that Javascript file along with MongoDB, so I'm guessing it's some NodeJS variant. You mention MeteorJS in the comments, so that's the documentation you need to add new features.
Do I need to add to this JS file to expand the API?
Simply: yes.
I want to know how to get data back from our MongoDB
Essentially this line is doing that. Of course, the response code shouldn't always be 200 and the content of the response string can be anything you want, but probably should be JSON, or at least something Android can parse
JsonRoutes.sendResult(res, 200, response);

Related

How to utilize AsyncTask for handling asynchronous RestRequests

I want to access an online API through an android application. For this purpose I have written easy to access functions to send requests via the android Volley package. However the app immediately displays 0s when I try to assign a value, that I have recieved through sending a request, to a TextView. I realize that this probably is because the function handles the Object as "null" because the response has not yet arrived and that I need to use AsyncTasks to handle this properly but the Developer Guide from Android Studio didn't really help me too much because, to be absolutely 100% honest with you, I'm not a software engineer and I'm absolutely lost at this point.
Here's some code on how I access the API:
org.json.JSONObject makeRequest(String URL, String method, String[] headers){
int reqType;
switch(method.toUpperCase()){
case "GET":
reqType = Request.Method.GET;
break;
case "DELETE":
reqType = Request.Method.DELETE;
break;
default:
return null;
}
Response.Listener<JSONObject> listener = new Response.Listener<JSONObject>(){
#Override
public void onResponse(JSONObject Response){
result = Response;
}
};
Response.ErrorListener err = new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
result = null;
}
};
JsonObjectRequest req = new JsonObjectRequest(reqType, URL, null, listener, err){
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put(headers[0], headers[1]);
return params;
}
};
;
rQ_volley.add(req);
return result;
}
And additionally some code on where I access the method above
JSONArray koordTargetArr = rBuild.makeRequestArr("https://nominatim.openstreetmap.org/search?q="+target+"&format=json&polygon=1&addressdetails=1", "get",headersLonLat);
if(koordTargetArr != null) {
JSONObject koordTargetOBJ = koordTargetArr.getJSONObject(0);
koordTarget = koordTargetOBJ.getString("lon").concat(",").concat(koordTargetOBJ.getString("lat"));
}
else return 0;
I would appreciate any help you could give me on things like where I implement the AsyncTask and how I build one. I have experience in the async library in Node.js if that helps at all.
EDIT:
This is NOT a duplicate of How to use java.net.URLConnection to fire and handle HTTP requests I already know how to send HTTP Requests, I don't know how to use android AsyncTask, HTTP Requests are NOT the topic of this question.
Have you considered using Retrofit?
It will handle, construction and deserialization of all your network needs without needing to use AsyncTask + custom utilities functions.

How to call List Item in SharePoint Using REST API in Android?

I'm want to consume share point rest API service to call from Android previously i use to call share point web service through the graph API but while generating token from graph API its not support in below URL, does any one have any solution about this problem.
https://mysharepoint.sharepoint.com/sites/MySite/_api/web/lists/getbytitle('Announcements')/Items
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, MSGRAPH_URL,
parameters,new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
/* Successfully called graph, process data and send to UI */
Log.d(TAG, "Response: " + response.toString());
updateGraphUI(response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d(TAG, "Error: " + error.toString());
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap<>();
headers.put("Authorization", "Bearer " + authResult.getAccessToken());
return headers;
}
};
Log.d(TAG, "Adding HTTP GET to Queue, Request: " + request.toString());
request.setRetryPolicy(new DefaultRetryPolicy(
3000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
queue.add(request);
I already tried with MSAL library but its does not work with this token.
Update: i used to call graph api for janrating token but i got 401 error with this above mention URL.
You are calling a SharePoint API, so you will need a SharePoint token instead of a Graph token. These are two separate APIs with different authentications.
To get a SharePoint token you will need to register an App in SharePoint itself or use the users username + password if available in your app.
Also see:
https://spshell.blogspot.com/2015/03/sharepoint-online-o365-oauth.html
https://shareyourpoint.net/2017/01/25/operations-using-rest-in-sharepoint-online-authorization/
For Graph, use an URL like this to get your list items:
https://graph.microsoft.com/v1.0/sites/{site-id}/lists/{list-id}/items?expand=fields(select=Column1,Column2)
You will probably need to do several calls to get your site ID and list ID first.
https://learn.microsoft.com/en-us/graph/api/listitem-list?view=graph-rest-1.0

send json to Laravel using postman and android

i am trying to send json using postman to Lavavel but i facing this error.
enter image description here
this is my json code:
{
"email":"test#test.com",
"password":"testtest"
}
and this is Laravel codes :
Route::get('/r','test#store');
and
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use DB;
use Log;
class test extends Controller
{
public function store(Request $request)
{
$email = $request->input('email');
$password = $request->input('password');
Log::info('test');
Log::info($email);
Log::info($password);
DB::table('login')->insert([
['email' => $email],
['password' => $password]
]);
}
}
also i trying using android for send data using volley and so checked Laravel logs :
Column 'email' cannot be null (this is Laravel logs)
and on android Logs:
E/Volley: [299] BasicNetwork.performRequest: Unexpected response code 500 for http://192.168.1.4:8000/r
D/error: com.android.volley.ServerErro
my android code is :
public class ApiService {
private final Context context;
public ApiService(Context context){
this.context=context;
}
public void loginUser(String email, String password, final OnLoginResponse onLoginResponse){
JSONObject requestJsonObject=new JSONObject();
try {
requestJsonObject.put("email",email);
requestJsonObject.put("password",password);
JsonObjectRequest request=new JsonObjectRequest(Request.Method.GET, "http://192.168.1.4:8000/r",requestJsonObject , new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("response",response.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("error",error.toString());
}
}) {
#Override
public Map getHeaders() throws AuthFailureError {
HashMap headers = new HashMap();
headers.put("Content-Type", "application/json");
return headers;
}
};
request.setRetryPolicy(new DefaultRetryPolicy(18000,DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
Volley.newRequestQueue(context).add(request);
} catch (JSONException e) {
Log.e(TAG, "loginUser: "+e.toString());
}
}
public interface OnLoginResponse{
void onResponse(boolean success);
}
}
I hope this helps people trying to search on how to send JSON data to laravel not only specific to android applications but to all. The goal of this solution is to identify whether you can send a JSON data to laravel or not.
First of all you have to download postman from https://www.getpostman.com/ to test if your API is really working or not.
Create a post request using postman. Be sure that you follow the example data below
Be sure that you set your Routes that would associate to the controller
This is the controller part that will show the JSON data you sent if it was successfully accepted or not.
And also, if ever you are trying to send POST data to laravel, by default they provided a CSRF Token which is applicable for the forms if you are going to use the MVC of laravel. For the meantime, we are going to take this down and comment it out. Just go to app/http/kernel.php
and now you'll get the following result from the code earlier
$json = json_decode($request['json']);
echo $json->{'email'};
echo "\n";
echo $json->{'password'};
We tested that we were able to send data to laravel. I hope this truly helps.
Wen you want to send data, you will want to use POST or PUT method on your postman, specially if you are sending a body, that means that you are sending data. Get method is used to retrieve data from a service.
Take a look into CRUD functions for more information.
Your postman should look something like this
Last in your android code try to change this line
JsonObjectRequest request=new JsonObjectRequest(Request.Method.GET, "http://192.168.1.4:8000/r",requestJsonObject , new Response.Listener<JSONObject>() {
to use Request.Method.POST

How can I return a String after client post from android to page JSP?

I am developing a web application for university project, where an android client sends to a java server an image, and after that the server compares the image with those in the database and it has to send a response as a String object to the client who invoked the server. How can i do it?
I use android-async-http to send the image from client and it works great, but i don't know how to send a response.
This is a partial code of the client:
public void makeHTTPCall(){
prgDialog.setMessage("Server Connection..);
AsyncHttpClient client=new AsyncHttpClient();
client.post(ipAddress,params, new AsyncHttpResponseHandler() {
#Override
public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
prgDialog.hide();
Snackbar.make(parentLayout,"Image uploaded.",Snackbar.LENGTH_LONG).show();
}
#Override
public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
prgDialog.hide();
if(statusCode==404){
Snackbar.make(parentLayout,"Page not found.",Snackbar.LENGTH_LONG).show();
}
else if(statusCode==500){
Snackbar.make(parentLayout,"Server problem.",Snackbar.LENGTH_LONG).show();
}else{
Snackbar.make(parentLayout,"Generic Error. code: "+statusCode,Snackbar.LENGTH_LONG).show();
}
}
});
}
and here the code from server:
<%
String imgEncodedStr = request.getParameter("image");
String fileName = request.getParameter("filename");
System.out.println("Filename: "+ fileName);
if(imgEncodedStr != null){
ManipolaImmagini.stringToImage(imgEncodedStr, fileName);
System.out.println("Inside if");
out.print("Image upload complete, Please check your directory");
} else{
System.out.println("Inside else");
out.print("Image is empty");
}%>
What you looking for is a WebService.
Here are some resources to start with that:
Difference between web services and servlet
Oracle Web Service Guide
Your problem could be related to:
Calling WebServices from JSP
I'm working on a similar project. I allready have my webservices and now I'm on Android side.
My webservices use Jersey. If your server is compatible, it's not so tricky to make a webservice and Jersey documentation is really good.
Server side
If needed, you have to put librairies in your project. If you use maven, you have to follow :
https://jersey.java.net/documentation/latest/modules-and-dependencies.html#dependencies
In you war project, to activate Jersey, an easy way could be to make a class as simple as this :
#javax.ws.rs.ApplicationPath("/url_to_your_webservices")
public class MyApplication extends ResourceConfig {
public MyApplication() {
// Association des classes de webservices
packages(true, "path.to.your.webservices.package");
}
}
Otherwise, there are other solutions described here :
https://jersey.java.net/documentation/latest/deployment.html
Next step, you have to create a Resource class which is your Webservice and could be something like that :
#Path("url_of_the_resource")
#RequestScoped
public class YourResource {
#GET
#Path("/url_of_the_method_inside_your_resource")
#Produces("application/txt")
#Consumes("image/jpeg")
public Response compareMyImage() {
// See how you can get your images and build your answer which could be what you want TXT, JSON, XML...
return Response.ok("Awnser Could be what you want.").build();
}
}
More details on how to construct webservices here :
https://docs.oracle.com/javaee/7/tutorial/partwebsvcs.htm#BNAYK
Client side
It's seems that there is a Jersey client for android :
https://blogs.oracle.com/japod/entry/jersey_2_x_client_on1
Otherwise, you can a traditionnal http client.
Of course, you have to adapt my examples to your case. Good luck, hope it helps.

Volley JsonObjectRequest Put is not working

I am making JsonObjectRequest with Put method but it is not working and getting "{"detail":"Method \"GET\" not allowed."}" error message.
It is working fine on Postman. See attached screenshots for more information.
I didn't modify JsonObjectRequest. I copy this code from google sample code from here "http://developer.android.com/training/volley/request.html".
I don't think this could be a bug in Volley. Please go through my code and let me know what I am doing wrong.
JsonObjectRequest jsObjRequest = new JsonObjectRequest
(Request.Method.PUT, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
hideDialog();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// TODO Auto-generated method stub
hideDialog();
}
})
{
#Override
public Map getHeaders() throws AuthFailureError {
Map headers = new HashMap();
headers.put("Authorization", "Token " + dm.readString("auth_token"));
return headers;
}
};
AppController.getInstance().addToRequestQueue(jsObjRequest);
Edit: I know in the screenshot it shows 400 bad request. It is because i need to pass 2 params ie {"dg_id":"80","delivery_ids":["90936"]}. With this params also i am getting the same error in Volley.
Sample auth_token Value: MTIzNDU2NzIzNDM6ZGVsaXZlcnlndXk=
Sample Body value: {"dg_id":"80","delivery_ids":["90936"]}
Add "/" at end of DELETE, PUT interface url,do check out the following snippet.
If a client issues a GET request to "/testdir/" (i.e., at the
directory).......It is interesting to take note that if a client issue
a GET request to "/testdir" (without specifying the directory path
"/"), the server returns a "301 Move Permanently" with a new
"Location" of "/testdir/", as follows.

Categories