Android(java)凌空不发送帖子请求

时间:2017-02-02 18:54:28

标签: java php android web-services web

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

这是我的项目。首先是我的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推荐的一般设计方法使用齐射。

其次,下一个使用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);

?>

我只检查第一个var是否设置,否则打印出来。它打印出文本,这意味着它没有设置...另外那些给我索引错误,因为它们显然是空的......

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

最后说明在运行应用程序后使用php脚本刷新页面时会发生什么:

php_problem

4 个答案:

答案 0 :(得分:0)

试试这个:

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

其中method是您的标记:例如"Register", "login" ..等。您也可以在没有Tag方法的情况下使用。

现在在你的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'

答案 1 :(得分:0)

答案 2 :(得分:0)

您还需要覆盖 getBodyContentType(),例如 getParams(),并将以下代码添加到其中。

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

答案 3 :(得分:0)

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