我如何在android工作室中启用httpclient?

时间:2015-08-29 14:04:35

标签: java android

帮助!如何在我的Android工作室中启用以下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 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

我最近不得不更改几乎所有代码,因为该库已被弃用。我相信从现在开始建议我们使用原始的Java网络库。

尝试以下

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

希望有所帮助

答案 2 :(得分:0)

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

答案 3 :(得分:0)

您还可以使用谷歌中的排球图书馆来完成工作。

使用该库的示例:

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

);