HttpClient已弃用/与PHP服务器连接 - Android API 22

时间:2015-06-30 16:18:39

标签: android httpclient

我正在尝试登录并注册一个Android应用程序。 我在将代码调整为API 22时遇到了问题。 虽然我知道我必须使用HttpURLConnection而不是HttpRequestParams等,并且已经这样做了,但我无法弄清楚如何调整代码以合并数据库服务器并存储我的PHP文件在那里。

下面大部分都是我无法弄清楚的。

HttpClient client = new DefaultHttpClient(httpRequestParams);
HttpPost post = new HttpPost(SERVER_ADDRESS + "FetchUserData.php");

有人可以帮忙吗?提前谢谢。

这里是完整的代码:

        @Override
        protected User doInBackground(Void... params) {

            ContentValues contentValues = new ContentValues();
            contentValues.put("username", user.username);
            contentValues.put("password", user.password);

            URL url = new URL(SERVER_ADDRESS);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setConnectTimeout(CONNECTION_TIMEOUT);
            conn.setReadTimeout(CONNECTION_TIMEOUT);

            HttpClient client = new DefaultHttpClient(httpRequestParams);
            HttpPost post = new HttpPost(SERVER_ADDRESS + "FetchUserData.php");

            User returnedUser = null;
            try {
                post.setEntity(new UrlEncodedFormEntity(dataToSend));
                HttpResponse httpResponse = client.execute(post);

                HttpEntity entity = httpResponse.getEntity();
                String result = EntityUtils.toString(entity);
                JSONObject jObject = new JSONObject(result);

                if(jObject.length() == 0) {
                    returnedUser = null;
                } else {
                    String mobile = jObject.getString("mobile");
                    String email = jObject.getString("email");

                    returnedUser = new User(mobile, email, user.mobile, user.email);
                }

            } catch(Exception e) {
                e.printStackTrace();
            }

            return returnedUser;
        }

1 个答案:

答案 0 :(得分:1)

首先:已经回答了 Sending Http request for Android 22+

第二:我已经开设了一个满足您需求的课程,允许您通过一行代码发送请求和接收响应(这也在上面的帖子中有解释)

以下是我班级的链接:

HttpRequest