Android: Posting a POST or JSON request to server

2019-06-10 22:51发布

I'm in the process of developing an Android app, which uses HTTP POST to send login data to a server. This all worked fine, until both the HTTPClient and the NameValuePair libraries were deprecated in recent updates.

I've Google'd a lot for new methods, and I know I should use Http(s)URLConnection for connecting to a server, but I can't get it to work properly and the Google Developers site doesn't provide an example either. I did use this piece of code but it won't work, throwing all sorts of syntax errors (missing ;'s and such).

Is there anyone who can provide an example of a working HTTP(s) request? Both POST and JSON are fine, as I can easily adjust the PHP code to receive JSON objects. Thanks in advance!

1条回答
做自己的国王
2楼-- · 2019-06-10 23:36

Use volley. Here is a scratch for you how to use it.

StringRequest strReq = new StringRequest(Request.Method.POST,
            <url>, new Response.Listener<String>() {

        @Override
        public void onResponse(String response) {
            Log.d(TAG, response.toString());

            try {
                //whatever format from response,do here...for eg:
                JSONObject responseObj = new JSONObject(response);
            //do parsing here after posting and response..
                }

            } catch (JSONException e) {
                Toast.makeText(getApplicationContext(),
                        "Error: " + e.getMessage(),
                        Toast.LENGTH_LONG).show();
            }

        }
    }, new Response.ErrorListener() {

        @Override
        public void onErrorResponse(VolleyError error) {
            Log.e(TAG, "Error: " + error.getMessage());
            Toast.makeText(getApplicationContext(),
                    error.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }) {

        @Override
        protected Map<String, String> getParams() {
            Map<String, String> params = new HashMap<String, String>();
            params.put("name", editText.getText().toString());
            Log.e(TAG, "Posting params: " + params.toString());
            return params;
        }

    };
查看更多
登录 后发表回答