简体   繁体   中英

Trying to send android volley post request to Laravel

I am using laravel 5.1 for the database connectivity and sending the post request form android to laravel.. but the exception is showing "server error"

Its my Android Code:-

package com.example.ankit.postrequest;

import android.app.DownloadManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;

import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

public class DataSent extends AppCompatActivity {

    private static final String KEY_USERNAME ="rohit" ;
    private static final String KEY_PASSWORD ="1234" ;
    private static final String KEY_EMAIL ="a@gmail.com" ;
    private static final String KEY_token ="xyz" ;
    EditText Etname,Etpass,Etmail,Et_token;
    RequestQueue insert;
    String insertUrl ="http://memorableshaadi.com/j";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Etmail = (EditText)findViewById(R.id.activity_booking_form_email);
        Etname = (EditText)findViewById(R.id.activity_booking_form_name);
        Etpass = (EditText)findViewById(R.id.activity_booking_form_dow);
        Et_token = (EditText)findViewById(R.id.activity_booking_form_token);
    }

    public void call(View v) {
          registerUser();
    }

    private void registerUser(){
        final String username = Etname.getText().toString().trim();
        final String password = Etpass.getText().toString().trim();
        final String email = Etmail.getText().toString().trim();
        final String token = Ettoken.getText().toString().trim();

        StringRequest stringRequest = new StringRequest(Request.Method.POST, insertUrl,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        Toast.makeText(DataSent.this, response, Toast.LENGTH_LONG).show();
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Toast.makeText(DataSent.this,error.toString(),Toast.LENGTH_LONG).show();
                    }
                }){
            @Override
            protected Map<String,String> getParams(){
                Map<String,String> params = new HashMap<String, String>();
                params.put(KEY_USERNAME,username);
                params.put(KEY_PASSWORD,password);
                params.put(KEY_EMAIL, email);
                params.put(KEY_token, token);
                return params;
            }

        };

        RequestQueue requestQueue = Volley.newRequestQueue(this);
        requestQueue.add(stringRequest);
    }

}

Laravel routes.php

<?php

Route::post('users','JsonController@data');

laravel JsonController.php

   <?php
namespace App\Http\Controllers;
use App\User;
use Illuminate\Support\Facades\Mail;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use DB;
use File;
use Storage;
use response;
use Illuminate\Contracts\Routing\ResponseFactory;
class JsonController extends Controller{
public function data(Request $dat){
            $user = $dat->username;
            $pass = $dat->password;
            $email = $dat->email;
            DB::table('user')->insert([
                    'user_name' => $user,
                    'user_email' => $pass, 
                    'user_password' => $email
            ]);
            echo($user.$pass.$email);
        }
}

There are two things you should take care of : First : The error you're facing is : TokenMismatchException in VerifyCsrfToken.php and the reason is because to build an authentication any request should passthrough your middleware and in Laravel Token must be passed so since you are using the post method you didn't pass it and it's missing your request so the easiest way to fix that is to add exceptions to your App\\Http\\Middleware\\VerifyCsrfToken.php

class VerifyCsrfToken extends BaseVerifier
{
/**
 * The URIs that should be excluded from CSRF verification.
 *
 * @var array
 */
protected $except = [
   /* Add here your URLs */ 
];
}

And your request will work just fine, and also you can use this library for handling Token Authentication jwt-auth . However there is something I should mention about your code: In your android code :

private static final String KEY_USERNAME ="rohit" ;
private static final String KEY_PASSWORD ="1234" ;
private static final String KEY_EMAIL ="a@gmail.com" ;
private static final String KEY_token ="xyz" ;

These keys will be used to match the request's values with the check function's values so you should first rename them to be just like the API source otherwise the check function won't get the values from any request so they should be like so :

private static final String KEY_USERNAME ="username" ;
private static final String KEY_PASSWORD ="password" ;
private static final String KEY_EMAIL ="email" ;

I hope this will help you )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM