简体   繁体   中英

how do i enable httpclient in android studios?

Help! How do i enable the following httpclient in my android studios? Can't seem to find NameValuePair, BasicNameValuePair, Httpclient, Httppost and apparently my HTTPConnectionParams are depracated? How do i resolve them?

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

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

I recently had to change almost all of my code because that library has been deprecated. I believe we have been advised to use the original Java net library from now on.

Try the following

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

Hope it helps

BasicNameValuePair is also deprecated. Use HashMap to send keys and values.

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

Use this method in order to post data to the "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();
}

You can also use the Volley Library from google to get your job done.

Example of using the library:

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

);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM