簡體   English   中英

使用Volley庫將JSON數據從客戶端發送到服務器

[英]Send json data from client to server using volley library

我想從客戶端向服務器發送一條簡單的消息(服務器不是本地主機)。 我使用Volley庫和POST方法。 當我運行代碼未建立連接時,LogCat打印:

05-30 12:19:05.930: D/memalloc(12085): /dev/pmem: Mapped buffer base:0x51dec000 size:3727360 offset:3112960 fd:48 
05-30 12:19:06.340: D/memalloc(12085): /dev/pmem: Mapped buffer base:0x5227a000 size:4382720 offset:3768320 fd:47
05-30 12:19:06.370: E/Volley(12085): [1] 2.onErrorResponse: Error:

客戶代碼:

String url = "http://myWebServer.eu";
RequestQueue queue;
JsonObjectRequest request;
Map<String, String> map = new HashMap<String, String>();

protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    queue = Volley.newRequestQueue(this);

    map.put("param1", "example");

    request = new JsonObjectRequest(Request.Method.POST, 

            url, 
            new JSONObject(map), 
            new Response.Listener<JSONObject>() { 
                @Override
                public void onResponse(JSONObject response) {

                    try {
                        VolleyLog.v("Response:%n %s", response.toString(7));
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }, new Response.ErrorListener() { 
                @Override
                public void onErrorResponse(VolleyError error) {

                    VolleyLog.e("Error: ", error.getMessage());
                }
            });

    queue.add(request);
}

PHP服務器代碼

$jsondata = $_POST['param1'];

$json = json_decode($jsondata,true);

echo $json ;

在這里,您嘗試將非json類型解碼為json。 $ post ['param1']是可以從應用程序請求到服務器的字符串值,只需打印$ post ['param1']是String格式而不是json

$jsondata = $_POST['param1'];

echo $json_encode($_POST)  ;

在你的PHP端寫下面的代碼:

$value = json_decode(file_get_contents('php://input'));
$json = $value->param1;

並且您還應該將響應的json格式發送回您的應用,如您在此行中所看到的(public void onResponse(JSONObject response))

還要在您的帖子中添加標題:

@Override
        public Map<String, String> getHeaders() throws AuthFailureError {
            HashMap<String, String> headers = new HashMap<String, String>();
            headers.put("Content-Type", "application/json");
            headers.put( "charset", "utf-8");
            return headers;
        }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM