我需要 Android 中 HttpClient 的替代选项来将数据发送到 PHP,因为它不再受支持

I need an alternative option to HttpClient in Android to send data to PHP as it is no longer supported

目前我正在使用 HttpClientHttpPostAndroid app 向我的 PHP server 发送数据,但所有这些方法在 API 中已被弃用22 并在 API 23 中删除,那么它的替代选项是什么?

我到处搜索,但我什么也没找到。

HttpClient 已弃用,现已删除:

org.apache.http.client.HttpClient:

This interface was deprecated in API level 22. Please use openConnection() instead. Please visit this webpage for further details.

意味着你应该切换到 java.net.URL.openConnection()

另请参阅新的 HttpURLConnection 文档。

你可以这样做:

URL url = new URL("http://some-server");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");

// read the response
System.out.println("Response Code: " + conn.getResponseCode());
InputStream in = new BufferedInputStream(conn.getInputStream());
String response = org.apache.commons.io.IOUtils.toString(in, "UTF-8");
System.out.println(response);

IOUtils 文档:Apache Commons IO
IOUtils Maven 依赖项:http://search.maven.org/#artifactdetails|org.apache.commons|commons-io|1.3.2|jar

以下代码在 AsyncTask 中:

在我的后台进程中:

String POST_PARAMS = "param1=" + params[0] + "&param2=" + params[1];
URL obj = null;
HttpURLConnection con = null;
try {
    obj = new URL(Config.YOUR_SERVER_URL);
    con = (HttpURLConnection) obj.openConnection();
    con.setRequestMethod("POST");

    // For POST only - BEGIN
    con.setDoOutput(true);
    OutputStream os = con.getOutputStream();
    os.write(POST_PARAMS.getBytes()); 
    os.flush();
    os.close();
    // For POST only - END

    int responseCode = con.getResponseCode();
    Log.i(TAG, "POST Response Code :: " + responseCode);

    if (responseCode == HttpURLConnection.HTTP_OK) { //success
         BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
         String inputLine;
         StringBuffer response = new StringBuffer();

         while ((inputLine = in.readLine()) != null) {
              response.append(inputLine);
         }
         in.close();

         // print result
            Log.i(TAG, response.toString());
            } else {
            Log.i(TAG, "POST request did not work.");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

参考: http://www.journaldev.com/7148/java-httpurlconnection-example-to-send-http-getpost-requests

我也遇到过这个问题,我自己解决了 class。 它基于 java.net,最多支持 android 的 API 24 请检查一下: HttpRequest.java

使用此 class 您可以轻松地:

  1. 发送 Http GET 请求
  2. 发送 Http POST 请求
  3. 发送 Http PUT 请求
  4. 发送 Http DELETE
  5. 不带额外数据参数发送请求并检查响应 HTTP status code
  6. 向请求添加自定义 HTTP Headers(使用可变参数)
  7. 将数据参数作为 String 查询添加到请求
  8. 将数据参数添加为 HashMap {key=value}
  9. 接受响应 String
  10. 接受响应 JSONObject
  11. 接受响应作​​为 byte [] 字节数组(对文件有用)

以及它们的任意组合 - 只需一行代码)

这里有几个例子:

//Consider next request: 
HttpRequest req=new HttpRequest("http://host:port/path");

示例 1:

//prepare Http Post request and send to "http://host:port/path" with data params name=Bubu and age=29, return true - if worked
req.prepare(HttpRequest.Method.POST).withData("name=Bubu&age=29").send();

示例 2

// prepare http get request,  send to "http://host:port/path" and read server's response as String 
req.prepare().sendAndReadString();

示例 3:

// prepare Http Post request and send to "http://host:port/path" with data params name=Bubu and age=29 and read server's response as JSONObject 
HashMap<String, String>params=new HashMap<>();
params.put("name", "Groot"); 
params.put("age", "29");
req.prepare(HttpRequest.Method.POST).withData(params).sendAndReadJSON();

示例 4

//send Http Post request to "http://url.com/b.c" in background  using AsyncTask
new AsyncTask<Void, Void, String>(){
        protected String doInBackground(Void[] params) {
            String response="";
            try {
                response=new HttpRequest("http://url.com/b.c").prepare(HttpRequest.Method.POST).sendAndReadString();
            } catch (Exception e) {
                response=e.getMessage();
            }
            return response;
        }
        protected void onPostExecute(String result) {
            //do something with response
        }
    }.execute(); 

示例 5:

//Send Http PUT request to: "http://some.url" with request header:
String json="{\"name\":\"Deadpool\",\"age\":40}";//JSON that we need to send
String url="http://some.url";//URL address where we need to send it 
HttpRequest req=new HttpRequest(url);//HttpRequest to url: "http://some.url"
req.withHeaders("Content-Type: application/json");//add request header: "Content-Type: application/json"
req.prepare(HttpRequest.Method.PUT);//Set HttpRequest method as PUT
req.withData(json);//Add json data to request body
JSONObject res=req.sendAndReadJSON();//Accept response as JSONObject

示例 6:

//Equivalent to previous example, but in a shorter way (using methods chaining):
String json="{\"name\":\"Deadpool\",\"age\":40}";//JSON that we need to send
String url="http://some.url";//URL address where we need to send it 
//Shortcut for example 5 complex request sending & reading response in one (chained) line
JSONObject res=new HttpRequest(url).withHeaders("Content-Type: application/json").prepare(HttpRequest.Method.PUT).withData(json).sendAndReadJSON();

例 7:

//Downloading file
byte [] file = new HttpRequest("http://some.file.url").prepare().sendAndReadBytes();
FileOutputStream fos = new FileOutputStream("smile.png");
fos.write(file);
fos.close();

这是我针对这个版本android 22`

中httpclient deprecated 的问题应用的解决方案
 public static final String USER_AGENT = "Mozilla/5.0";



public static String sendPost(String _url,Map<String,String> parameter)  {
    StringBuilder params=new StringBuilder("");
    String result="";
    try {
    for(String s:parameter.keySet()){
        params.append("&"+s+"=");

            params.append(URLEncoder.encode(parameter.get(s),"UTF-8"));
    }


    String url =_url;
    URL obj = new URL(_url);
    HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();

    con.setRequestMethod("POST");
    con.setRequestProperty("User-Agent", USER_AGENT);
    con.setRequestProperty("Accept-Language", "UTF-8");

    con.setDoOutput(true);
    OutputStreamWriter outputStreamWriter = new OutputStreamWriter(con.getOutputStream());
    outputStreamWriter.write(params.toString());
    outputStreamWriter.flush();

    int responseCode = con.getResponseCode();
    System.out.println("\nSending 'POST' request to URL : " + url);
    System.out.println("Post parameters : " + params);
    System.out.println("Response Code : " + responseCode);

    BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
    String inputLine;
    StringBuffer response = new StringBuffer();

    while ((inputLine = in.readLine()) != null) {
        response.append(inputLine + "\n");
    }
    in.close();

        result = response.toString();
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (ProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }catch (Exception e) {
        e.printStackTrace();
    }finally {
    return  result;
    }

}

我在使用 HttpClentHttpPost 方法时遇到了类似的问题,因为我不想更改我的代码,所以我在build.gradle(module) 文件,方法是从 buildToolsVersion“23.0.1 rc3”中删除 'rc3',它对我有用。希望对您有所帮助。

Which client is best?

Apache HTTP client has fewer bugs on Eclair and Froyo. It is the best choice for these releases.

For Gingerbread and better, HttpURLConnection is the best choice. Its simple API and small size makes it great fit for Android...

参考 here 了解更多信息(Android 开发者博客)

您可以继续使用 HttpClient。 Google 仅弃用了他们自己版本的 Apache 组件。您可以像我在 post:

中描述的那样安装 Apache 的 HttpClient 的全新、强大且未弃用的版本

如果针对 API 22 岁及以上,则应将以下行添加到 build.gradle

dependencies {
    compile group: 'org.apache.httpcomponents' , name: 'httpclient-android' , version: '4.3.5.1'
}

如果针对 API 23 及更高版本,则应将以下行添加到 build.gradle

dependencies {
    compile group: 'cz.msebera.android' , name: 'httpclient', version: '4.4.1.1'
}

如果还想使用httpclient库,在Android Marshmallow (sdk 23)中,可以添加:

useLibrary 'org.apache.http.legacy'

到 android {} 部分中的 build.gradle 作为解决方法。这似乎是某些 Google 自己的 gms 库所必需的!

您可以使用我易于使用的自定义 class。 只需创建一个抽象对象 class(Anonymous) 并定义 onsuccess() 和 onfail() 方法。 https://github.com/creativo123/POSTConnection