有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何在安卓 Studio中启用httpclient?

救命啊!如何在我的安卓 Studio中启用以下httpclient?似乎找不到NameValuePair、BasicNameValuePair、Httpclient、Httppost,显然我的HTTPConnectionParams被删除了?如何解决这些问题

ArrayList<NameValuePair> dataToSend = new ArrayList<>();
            dataToSend.add(new BasicNameValuePair("name",user.name));
            dataToSend.add(new BasicNameValuePair("email",user.email));
            dataToSend.add(new BasicNameValuePair("password",user.password));

            HttpParams httpRequestParams = new BasicHttpParams();
            HttpConnectionParams.setConnectionTimeout(httpRequestParams, CONNECTION_TIMEOUT);
            HttpConnectionParams.setSoTimeout(httpRequestParams, CONNECTION_TIMEOUT);

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

            try{
                post.setEntity(new UrlEncodedFormEntity(dataToSend));
                client.execute(post);
            }catch (Exception e) {
                e.printStackTrace();
            }

共 (4) 个答案

  1. # 1 楼答案

    我假设您可能正在使用sdk 23+,尝试使用URLConnection或降级到sdk 22

  2. # 2 楼答案

    我最近不得不修改几乎所有的代码,因为那个库已经被弃用了。我相信有人建议我们从现在开始使用最初的Java net库

    试试下面的方法

    try{
        URL url = new URL(SERVER_ADDRESS + "Register.php");
        HttpURLConnection connection = (HttpURLConnection)url.openConnection();
        connection.setRequestMethod("POST");
        connection.setDoOutput(true);
        connection.setConnectTimeout(CONNECTION_TIMEOUT);
        String postData = URLEncoder.encode("name","UTF-8")
                            +"="+URLEncoder.encode(user.name,"UTF-8");
        postData += "&"+URLEncoder.encode("email","UTF-8")
                            +"="+URLEncoder.encode(user.email,"UTF-8");
        postData += "&"+URLEncoder.encode("password","UTF-8")
                            +"="+URLEncoder.encode(user.password,"UTF-8");
        OutputStreamWriter outputStreamWriter = new
        OutputStreamWriter(connection.getOutputStream());
        outputStreamWriter.write(postData);
        outputStreamWriter.flush();
        outputStreamWriter.close();
      }catch(IOException e){
        e.printStackTrace();
      }
    

    希望能有帮助

  3. # 3 楼答案

    您还可以使用谷歌截击库来完成您的工作

    使用库的示例:

    RequestQueue queue = Volley.newRequestQueue(activity);
                    StringRequest strRequest = new StringRequest(Request.Method.POST, "Your URL",
                            new Response.Listener<String>() {
                                @Override
                                public void onResponse(String response) {
                                    VolleyLog.d("Home_Fragment", "Error: " + response);
                                    Toast.makeText(activity, "Success", Toast.LENGTH_SHORT).show();
                                }
                            },
                            new Response.ErrorListener() {
                                @Override
                                public void onErrorResponse(VolleyError error) {
                                    VolleyLog.d(getApplicationContext(), "Error: " + error.getMessage());
                                    Toast.makeText(activity, error.toString(), Toast.LENGTH_SHORT).show();
                                }
                            }) {
                        @Override
                        protected Map<String, String> getParams() {
                            Map<String, String> params = new HashMap<>();
                            params.put("name", user.name);
                            params.put("email", user.email;
                            params.put("password", user.password);
    
                            return params;
                        }
                    };
                    queue.add(strRequest);
    
    );
    
  4. # 4 楼答案

    BasicNameValuePair也不推荐使用。使用HashMap发送键和值

    HashMap文档:http://developer.android.com/reference/java/util/HashMap.html

    使用此方法将数据发布到“yourFiles.php”

    public String performPostCall(String requestURL, HashMap<String, String> postDataParams) {
    
        URL url;
        String response = "";
        try {
            url = new URL(requestURL);
    
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setReadTimeout(15000);
            conn.setConnectTimeout(15000);
            conn.setRequestMethod("POST");
            conn.setDoInput(true);
            conn.setDoOutput(true);
    
    
            OutputStream os = conn.getOutputStream();
            BufferedWriter writer = new BufferedWriter(
                    new OutputStreamWriter(os, "UTF-8"));
            writer.write(getPostDataString(postDataParams));
    
            writer.flush();
            writer.close();
            os.close();
            int responseCode=conn.getResponseCode();
    
            if (responseCode == HttpsURLConnection.HTTP_OK) {
                String line;
                BufferedReader br=new BufferedReader(new InputStreamReader(conn.getInputStream()));
                while ((line=br.readLine()) != null) {
                    response+=line;
                }
            }
            else {
                response="";
    
                throw new HttpException(responseCode+"");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    
        return response;
    }
    private String getPostDataString(Map<String, String> params) throws UnsupportedEncodingException {
        StringBuilder result = new StringBuilder();
        boolean first = true;
        for(Map.Entry<String, String> entry : params.entrySet()){
            if (first)
                first = false;
            else
                result.append("&");
    
            result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
            result.append("=");
            result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
        }
    
        return result.toString();
    }