繁体   English   中英

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

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

在阅读了许多看起来相似的帖子后,这些都是关于 JSON 请求,而不是 StringRequests。 我正在为我的 Android 应用程序使用 volley API,并且我正在学习有关使用 volley 的应用程序与使用 php 处理的服务器之间交互的教程。 然而,出于某种原因,我的数据没有发送到 php 部分,因为当我尝试访问网络服务器上的数据时,它指出变量为空。

这是我的项目。 首先是我的 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);
    }

}

我相信上面的课程应该很好而且很好(99%肯定),因为我遵循Android / Google使用volley推荐的通用设计方法。

其次,下一个使用 Server_singleton 的文件。 这是魔法发生的地方,最有可能的错误是在这里的某个地方:

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


    }

}

上面的代码有效。 但它应该将国家、纬度等发布到我的网络服务器...

这是我的 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);

?>

我只检查第一个变量是否设置,否则打印出来。 它打印出文本,这意味着它没有设置......其他的也会给我索引错误,因为它们显然是空的......

我究竟做错了什么? 几天来我一直在摆弄这个问题,我无法弄清楚我错在哪里。

最后是运行应用程序后使用 php 脚本刷新页面时发生的情况的图片:

php_问题

尝试这个:

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

其中方法是您的标签:如"Register", "login"您也可以使用不带标签的方法。

现在在您的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);
        }
    }
}

确保在清单中设置权限:

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

build.gradle使用:

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

您还需要像getParams()一样覆盖getBodyContentType()并将以下代码放入其中。

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

您显示的图片描述了您的 PHP 脚本中可能存在错误。 $ 符号可能不与脚本中使用的变量一起出现,或者任何其他脚本错误导致此类 UI 作为运行 php 脚本的结果出现。

暂无
暂无

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

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