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

Java 我需要一个替代Android中HttpClient的选项来将数据发送到PHP,因为它不再受支持,java,android,api,http-post,apache-commons-httpclient,Java,Android,Api,Http Post,Apache Commons Httpclient,目前,我正在使用HttpClient,HttpPost从Android应用程序向我的PHP服务器发送数据,但所有这些方法在API 22中都被弃用,在API 23中被删除,那么有哪些替代选项呢 我到处搜索,但什么也没找到。已弃用,现在已删除: org.apache.http.client.HttpClient: 此接口在API级别22中被弃用。 请改用openConnection()。详情请浏览本网页 这意味着您应该切换到java.net.URL.openConnection() 另请参见新文档

目前,我正在使用
HttpClient
HttpPost
Android应用程序
向我的
PHP服务器
发送数据,但所有这些方法在API 22中都被弃用,在API 23中被删除,那么有哪些替代选项呢

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

已弃用,现在已删除:

org.apache.http.client.HttpClient

此接口在API级别22中被弃用。 请改用openConnection()。详情请浏览本网页

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

另请参见新文档

以下是您如何做到这一点:

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
文档:

IOUtils
Maven依赖项:

以下代码位于异步任务中:

在我的后台进程中:

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

我也遇到了这个问题,我自己制作了一个类来解决这个问题。 它基于java.net,最多支持android的API 24 请查看:

使用该类,您可以轻松地:

  • 发送Http
    GET
    请求
  • 发送Http
    POST
    请求
  • 发送Http
    PUT
    请求
  • 发送Http
    DELETE
  • 发送不带额外数据参数的请求并检查响应
    HTTP状态码
  • 向请求添加自定义
    HTTP头文件
    (使用varargs)
  • 将数据参数作为
    String
    查询添加到请求
  • 将数据参数添加为
    HashMap
    {key=value}
  • 接受响应为
    字符串
  • 接受响应为
    JSONObject
  • 将响应接受为字节数组(对文件有用)
  • 以及它们的任意组合(只需一行代码)

    以下是几个例子:

    //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();
    
    // 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();
    
    //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
    
    //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();
    
    //Downloading file
    byte [] file = new HttpRequest("http://some.file.url").prepare().sendAndReadBytes();
    FileOutputStream fos = new FileOutputStream("smile.png");
    fos.write(file);
    fos.close();
    
    示例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, return true - if worked
    req.prepare(HttpRequest.Method.POST).withData("name=Bubu&age=29").send();
    
    // 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();
    
    //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
    
    //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();
    
    //Downloading file
    byte [] file = new HttpRequest("http://some.file.url").prepare().sendAndReadBytes();
    FileOutputStream fos = new FileOutputStream("smile.png");
    fos.write(file);
    fos.close();
    
    示例6

    //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();
    
    // 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();
    
    //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
    
    //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();
    
    //Downloading file
    byte [] file = new HttpRequest("http://some.file.url").prepare().sendAndReadBytes();
    FileOutputStream fos = new FileOutputStream("smile.png");
    fos.write(file);
    fos.close();
    
    示例7

    //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();
    
    // 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();
    
    //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
    
    //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();
    
    //Downloading file
    byte [] file = new HttpRequest("http://some.file.url").prepare().sendAndReadBytes();
    FileOutputStream fos = new FileOutputStream("smile.png");
    fos.write(file);
    fos.close();
    

    这是我应用于httpclient在这个版本的android 22中不推荐使用的问题的解决方案`

     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;
        }
    
    }
    
    publicstaticfinalstringuser\u-AGENT=“Mozilla/5.0”;
    公共静态字符串sendPost(字符串_url,映射参数){
    StringBuilder参数=新StringBuilder(“”);
    字符串结果=”;
    试一试{
    对于(字符串s:parameter.keySet()){
    参数追加(&“+s+”=”);
    params.append(URLEncoder.encode(parameter.get),“UTF-8”);
    }
    字符串url=\uURL;
    URL obj=新URL(_URL);
    HttpsURLConnection con=(HttpsURLConnection)obj.openConnection();
    con.setRequestMethod(“POST”);
    con.setRequestProperty(“用户代理”,用户代理);
    con.setRequestProperty(“接受语言”、“UTF-8”);
    con.设置输出(真);
    OutputStreamWriter OutputStreamWriter=新的OutputStreamWriter(con.getOutputStream());
    outputStreamWriter.write(params.toString());
    outputStreamWriter.flush();
    int responseCode=con.getResponseCode();
    System.out.println(“\n向URL发送'POST'请求:“+URL”);
    System.out.println(“Post参数:“+params”);
    System.out.println(“响应代码:“+responseCode”);
    BufferedReader in=新的BufferedReader(新的InputStreamReader(con.getInputStream());
    字符串输入线;
    StringBuffer响应=新的StringBuffer();
    而((inputLine=in.readLine())!=null){
    响应。追加(inputLine+“\n”);
    }
    in.close();
    结果=response.toString();
    }捕获(不支持的编码异常e){
    e、 printStackTrace();
    }捕获(格式错误){
    e、 printStackTrace();
    }捕获(协议例外e){
    e、 printStackTrace();
    }捕获(IOE异常){
    e、 printStackTrace();
    }捕获(例外e){
    e、 printStackTrace();
    }最后{
    返回结果;
    }
    }
    
    我在使用HttpClentHttpPost方法时遇到了类似的问题,因为我不想更改我的代码,所以我在build.gradle(模块)文件中找到了替代选项,从buildToolsVersion“23.0.1 rc3”中删除了“rc3”,这对我很有效。希望有帮助

    哪个客户最好

    ApacheHTTP客户端在Eclair和Froyo上的bug较少。这是最好的 这些版本的选择

    对于姜饼和更好的产品,HttpURLConnection是最佳选择。它的 简单的API和小尺寸使它非常适合Android


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

    您可以继续使用HttpClient。谷歌只反对他们自己版本的Apache组件。您可以安装Apache的HttpClient的全新、功能强大且未弃用的版本,如我在本文中所述:

    如果针对API 22及更旧版本,则应在build.gradle中添加以下行

    dependencies {
        compile group: 'org.apache.httpcomponents' , name: 'httpclient-android' , version: '4.3.5.1'
    }
    
    dependencies {
        compile group: 'cz.msebera.android' , name: 'httpclient', version: '4.4.1.1'
    }
    
    如果针对API 23及更高版本,则应在build.gradle中添加以下行

    dependencies {
        compile group: 'org.apache.httpcomponents' , name: 'httpclient-android' , version: '4.3.5.1'
    }
    
    dependencies {
        compile group: 'cz.msebera.android' , name: 'httpclient', version: '4.4.1.1'
    }
    
    如果仍要使用httpclient库,在Android Marshmallow(sdk 23)中,您可以添加:

    useLibrary 'org.apache.http.legacy'
    

    在android{}部分中构建.gradle作为一种解决方法。这似乎是谷歌自己的一些gms库所必需的

    您可以使用我的易于使用的自定义类。 只需创建抽象类(匿名)的对象并定义onsuccess()和onfail()方法。

    您应该澄清您所处的平台(java、php、ruby?)和您现在使用的library+版本,以及您试图更新到的library+版本(包括确切版本和库名)。我正在使用HttpPost和HttpClient从Android应用程序向PHP发送数据,但这些方法在API 22的新更新中已被弃用,因此我需要一些选项来解决此问题。您的答案中的
    IOUtils
    是什么?通过添加指向
    公用IO
    的链接来改进答案(
    IOUtils
    )文档和maven搜索站点。看起来