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
Related
Hi there I am struggling to understand how exactly Volley request works. I have done similar things in NodeJs and the process seemed more intuitive.
String url = "http://my-json-feed";
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest
(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
//All I want is to use the response outside this scope
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// TODO: Handle error
}
});
MySingleton.getInstance(this).addToRequestQueue(jsonObjectRequest);
//Example: How can I access the response here or in any other class?
In NodeJS this same process looks similar to this (with the help of node-fetch)
const response = await fetch(url);
const json = await response.json();
console.log(json);
And I can basically access json from anywhere in the same file or I can return it from the current function and use it anywhere where I call that function. I want to ask how can I do something similar in Java?
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
I am attempting to get a user's Reddit front page. I have successfully received an Auth Token via the Token Retrieval (code flow). I have managed to get the expected JSON response via Postman, but cannot produce the same results with Retrofit. The request seems to be timing out as onFailure() is being triggered in the callback. I am using the scopes: identity, mysubreddits, and read.
Additional note: I have got a 401 and 403 response with the code below when using insufficient scopes and using an expired Auth Token respectively.
Relevant constants:
redditToken = (actual auth token String)
RedditConstants.REDDIT_BASE_URL_OAUTH2 = "https://oauth.reddit.com"
Relevant method Section:
if (redditToken != null) {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(RedditConstants.REDDIT_BASE_URL_OAUTH2)
.addConverterFactory(GsonConverterFactory.create())
.build();
Api api = retrofit.create(Api.class);
Map<String, String> headers = new HashMap<>();
headers.put("Authorization", "bearer " + redditToken);
headers.put("User-Agent", RedditConstants.REDDIT_USER_AGENT);
Call<RedditFeed> call = api.getFeed(headers);
call.enqueue(new Callback<RedditFeed>() {
#Override
public void onResponse(Call<RedditFeed> call, Response<RedditFeed> response) {
Log.d("FINDME", "response "+ response.toString());
if (response.isSuccessful()) {
Log.d("FINDME", "response was a success! we got the feed!");
} else {
Log.d("FINDME", "responce was not successfull triggered");
}
}
#Override
public void onFailure(Call<RedditFeed> call, Throwable t) {
Log.d("FINDME", "onFailure called from populateRedditFeed");
}
});
} else {
Toast.makeText(this, "Please Login with Reddit", Toast.LENGTH_SHORT).show();
}
Retrofit Interface:
public interface Api {
#GET(".")
Call<RedditFeed> getFeed (
#HeaderMap Map<String, String> headers
);
}
Log Results:
D/NetworkSecurityConfig: No Network Security Config specified, using
platform default
I/zygote: Do full code cache collection, code=123KB, data=105KB
After code cache collection, code=111KB, data=79KB
D/FINDME: onFailure called from populateRedditFeed
Postman Success:
After many starts and stops, seemingly randomly getting either a 200 or calling onFailure() I discovered the problem in one of my Retrofit model classes. The JSON response from Reddit contains a field that can either be a long or boolean. I had it defined as a boolean in my java class which threw an llegalStateException when it was returned as a long.
type name description
special edited false if not edited, edit date in UTC epoch-seconds
otherwise. NOTE: for some old edited comments on reddit.com, this will
be set to true instead of edit date.
*I'm unsure how to deal with this duality of types in java so for now I've commented out the field and the code works as expected.
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);
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.