安卓:发布帖子或JSON请求到服务器,而所有的德precated功能有的、功能、服务器、帖子

2023-09-08 08:42:33 作者:堕落?让我享受你的全部▓

我在开发一个Android应用程序,它采用HTTP POST来登录数据发送到服务器的过程。这一切都工作得很好,直到两个HttpClient的和的NameValuePair图书馆是德$ P $在最近的更新pcated。

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.

我Google'd了很多新的方法,我知道我应该使用HTTP(S)的URLConnection连接到服务器,但我不能让它正常工作和谷歌开发者网站不或者提供一个例子。我没有使用这块code 的但它不会工作,扔语法错误百般(失踪;公司等等)。

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

是否有任何人谁可以提供一个工作的HTTP(S)请求的例子? POST和JSON都很好,我可以很容易地调整PHP code接收JSON对象。在此先感谢!

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!

推荐答案

使用抽射。这是给你一个从无到有如何使用它。

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

    };