Android Studio - 旧命令如httpparams,httpclient不再起作用

3

一些命令,例如HttpClientHttpPost无法正常工作。有人能帮我吗?

 @Override
    protected users doInBackground(Void... params){
        Map<String, String> dataToSend = new HashMap<>();
        dataToSend.put("x", users.x + "");
        dataToSend.put("y", users.y);

        URL url = new URL(SERVER_ADRESS);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        HttpParams httpRequestPramas = new BasicHttpParams();
        conn.setConnectionTimeout(httpRequestPramas, CONNECTION_TIME);
        HttpConnectionParams.setSoTimeout(httpRequestPramas, CONNECTION_TIME);

        HttpClient client = new DefaultHttpClient(httpRequestPramas);
        HttpPost post = new HttpPost(SERVER_ADRESS + "login.php");

        users returnedusers = 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){
                users = null;
            }else{
                String vorname = jObject.getString("y");
                int kundennummer = jObject.getInt("x");

                returnedusers = new users(users.y, users.x);

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

        return returnedusers;
    }

感谢您的帮助。

导入已经存在吗? - Sandeep Kaul
1
无法工作?或被标记为弃用?...另外,为什么您同时使用URLConnection和apache?...像“HttpClient”这样的命令,您是指类吗? - Selvin
一些已被标记为过时。 - Anna Katzen
@Rene M. 我正在尝试做这个 https://www.youtube.com/watch?v=vGk_EdI5qj0 ~19:40min - Anna Katzen
那么请在你的问题中解释这个,否则恶意用户会将你的问题投票至消失。 - Rene M.
显示剩余3条评论
1个回答

3
尝试这种方式。
URL url = new URL("http://example.sitedemo.service.php");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
Uri.Builder builder = new Uri.Builder().appendQueryParameter("username", "maven")
                                       .appendQueryParameter("password", "123");
String query = builder.build().getEncodedQuery();

OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
writer.write(query);
writer.flush();
writer.close();
os.close();

conn.connect();

InputStream in = new BufferedInputStream(conn.getInputStream());
response = IOUtils.toString(in, "UTF-8");

ref- android.net.Uri.Builder


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接