简体   繁体   English

Android(java)截击不发送发布请求

[英]Android(java) volley not sending post request

After reading MANY posts that seem similar, these were all about JSON requests, not StringRequests.在阅读了许多看起来相似的帖子后,这些都是关于 JSON 请求,而不是 StringRequests。 I am using volley API for my Android application, and I am following a tutorial on interaction between my app using volley and my server which is handled with php.我正在为我的 Android 应用程序使用 volley API,并且我正在学习有关使用 volley 的应用程序与使用 php 处理的服务器之间交互的教程。 For some reason however, my data is not sent to the php part, because when I try to access the data on the webserver, it states that the variables are empty.然而,出于某种原因,我的数据没有发送到 php 部分,因为当我尝试访问网络服务器上的数据时,它指出变量为空。

Here is my project.这是我的项目。 First off is my Singleton class which sets up ONE requestqueue:首先是我的 Singleton 类,它设置了一个请求队列:

import android.content.Context;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.Volley;


public class Server_singleton
{
    private static Server_singleton anInstance;
    private RequestQueue requestQueue;
    private static Context aCtx;

    private Server_singleton(Context context)
    {
        aCtx = context;
        requestQueue = getRequestQueue();
    }

    public static synchronized Server_singleton getInstance(Context context)
    {
        if(anInstance == null)
        {
            anInstance = new Server_singleton(context);
        }
        return anInstance;
    }

    public RequestQueue getRequestQueue()
    {
        if(requestQueue == null)
        {
            requestQueue = Volley.newRequestQueue(aCtx.getApplicationContext());
        }
        return requestQueue;
    }

    public <T> void addToRequestQueue(Request<T> request)
    {
        requestQueue.add(request);
    }

}

This above class should be all nice and fine I believe(99% certain), since I follow a general design approach recommended by Android/Google using volley.我相信上面的课程应该很好而且很好(99%肯定),因为我遵循Android / Google使用volley推荐的通用设计方法。

Secondly, the next file which uses Server_singleton.其次,下一个使用 Server_singleton 的文件。 Here is where the magic happens, and most likely the mistake is in here some place:这是魔法发生的地方,最有可能的错误是在这里的某个地方:

import android.content.Context;
import android.util.Log;

import com.android.volley.AuthFailureError;
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 java.util.HashMap;
import java.util.Map;

/**
 * 
 *
 * This class handles requests to web server by using Google Volley API
 * Google Volley API is very powerful and abstracts many low-level details when establishing
 * connection with a web server.
 * Volley API does not run on the main thread, which is the correct way of doing it in android.
 * If it was not doing work in a background thread, the main thread would be blocked(perhaps).
 * This is all done in an asynchronous way, which means that methods may behave somewhat
 * different than you would expect. A method which returns a string for example
 * may return a null object, before it is actually done waiting on the response from server
 * This means that we have to introduce callback methods with for instance interfaces.
 */


public class Server_interaction
{
    String server_url = "http://hiddenfromyou/update_location.php"; //correct ip in my code, but hidden here
    String response_string;
    RequestQueue queue;
    Context context;

    public Server_interaction(Context context)
    {
         this.context = context;
         queue = Server_singleton.getInstance(context).getRequestQueue();
    }


    public static final String TAG = Server_interaction.class.getSimpleName();

    public void post_request(final VolleyCallback callback)
    {
        StringRequest stringRequest = new StringRequest(Request.Method.POST, server_url,
                new Response.Listener<String>()
                {
                    @Override
                    public void onResponse(String response)
                    {
                        response_string = response;
                        callback.onSuccess(response_string);
                        //requestQueue.stop();
                        Log.i(TAG, "the response is: "+ response_string);

                    }
                }
                , new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error){
                        response_string = "Something went wrong";
                        //error.printstacktrace()
                        //requestQueue.stop();
                        Log.i(TAG, "something went wrong. Is the server up and running?");
                    }

                })
        {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {

                String the_name = "olaf";
                String the_mail = "lalalal";
                String the_country = "Norway";
                String the_latitude = "33";
                String the_longitude = "99";


                Map<String, String> params = new HashMap<String, String>();
                params.put("name", the_name);
                params.put("email", the_mail);
                params.put("country", the_country);
                params.put("latitude", String.valueOf(the_latitude));
                params.put("longitude", String.valueOf(the_longitude));

                Log.i(TAG, "inside getparams : "+params);
                return params;
            }
        };//stringrequest parameter end

        //add request to requestqueue
        Log.i(TAG, "the stringrequest: "+ stringRequest);
        Server_singleton.getInstance(context).addToRequestQueue(stringRequest);
        Log.i(TAG, "the response again:: "+ response_string);


    }

}

The above code WORKS.上面的代码有效。 But it should POST country, latitute etc to my webserver...但它应该将国家、纬度等发布到我的网络服务器...

Here is my PHP script:这是我的 PHP 脚本:

<?php

$email = isset($_POST["email"]) ? $_POST["email"] : print("received nothing!");               //receive from android app
$phonenumber = $_POST["phonenumber"]; //receive from android app
$country = $_POST["country"];         //receive from android app
$latitude = $_POST["latitude"];       //receive from android app
$longitude = $_POST["longitude"];   

$username_for_localhost = "root";
$password_for_localhost = "";
$host = "localhost";
$db_name = "exigentia_location_db";

$con = mysqli_connect($host, $username_for_localhost, $password_for_localhost, $db_name);

if($con)
{
    echo "Connection succeded";
}

else
{
    echo "Connection failed";
}


$sql = "insert into person values('".$email."', '".$phonenumber."', '".$country."', '".$location."', '".$latitude."', '".$longitude."');";

if(mysqli_query($con, $sql))
{
    echo "data insertion succeeded";
}

else
{
    echo "data insertion failed";
}




mysqli_close($con);

?>

I check only the first var if its set, and else print out.我只检查第一个变量是否设置,否则打印出来。 It prints out the text, which means it is not set...Also the other ones give me index errors, since they obviously are empty...它打印出文本,这意味着它没有设置......其他的也会给我索引错误,因为它们显然是空的......

What am I doing wrong?我究竟做错了什么? I have been fiddling with this problem for days, and I cannot figure out where I am wrong.几天来我一直在摆弄这个问题,我无法弄清楚我错在哪里。

Finally a pic of what happens when I refresh my page with the php script after running the app:最后是运行应用程序后使用 php 脚本刷新页面时发生的情况的图片:

php_问题

try this:尝试这个:

Server_singleton.getInstance().addToRequestQueue(request, method);

where method is your tag: like "Register", "login" ..etc.You can use without Tag method also.其中方法是您的标签:如"Register", "login"您也可以使用不带标签的方法。

Now in your Server_singleton write this code:现在在您的Server_singleton编写以下代码:

 public class Server_singleton extends Application {


    public static final String TAG = Server_singleton.class.getSimpleName();

    private RequestQueue mRequestQueue;
    private static Server_singleton mInstance;

    @Override
    public void onCreate() {
        super.onCreate();
        mInstance = this;
    }

    public static synchronized Server_singleton getInstance() {
        return mInstance;
    }

    public RequestQueue getRequestQueue() {
        if (mRequestQueue == null) {
            mRequestQueue = Volley.newRequestQueue(getApplicationContext());
        }

        return mRequestQueue;
    }

    public <T> void addToRequestQueue(Request<T> req, String tag) {
        req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
        getRequestQueue().add(req);
    }

    public <T> void addToRequestQueue(Request<T> req) {
        req.setTag(TAG);
        getRequestQueue().add(req);
    }

    public void cancelPendingRequests(Object tag) {
        if (mRequestQueue != null) {
            mRequestQueue.cancelAll(tag);
        }
    }
}

Make sure you set the permission in manifest:确保在清单中设置权限:

<uses-permission android:name="android.permission.INTERNET" />

And in build.gradle use:build.gradle使用:

 compile 'com.mcxiaoke.volley:library-aar:1.0.0'

You need to also override the getBodyContentType() like getParams() and put the following code in it.您还需要像getParams()一样覆盖getBodyContentType()并将以下代码放入其中。

@Override
public String getBodyContentType() {
   return "application/x-www-form-urlencoded; charset=UTF-8";
}

The picture you have shown depicts that there may be errors in your PHP script.您显示的图片描述了您的 PHP 脚本中可能存在错误。 The $ sign may not be present with the variables used in the script, or any other scripting errors cause such UI to appear as a result of running php script. $ 符号可能不与脚本中使用的变量一起出现,或者任何其他脚本错误导致此类 UI 作为运行 php 脚本的结果出现。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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