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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29058727/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 07:17:24  来源:igfitidea点击:

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

javaandroidapihttp-postapache-commons-httpclient

提问by priyank

Currently I'm using HttpClient, HttpPostto send data to my PHP serverfrom an Android appbut all those methods were deprecated in API 22 and removed in API 23, so what are the alternative options to it?

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

I searched everywhere but I didn't find anything.

我到处搜索,但没有找到任何东西。

采纳答案by fateddy

The HttpClientwas deprecated and now removed:

HttpClient的已被废弃,现在删除:

org.apache.http.client.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.

此接口在 API 级别 22 中已弃用。请改用 openConnection()。请访问此网页了解更多详情。

means that you should switch to java.net.URL.openConnection().

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

See also the new HttpURLConnectiondocumentation.

另请参阅新的HttpURLConnection文档。

Here's how you could do it:

你可以这样做:

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

IOUtilsdocumentation: Apache Commons IO
IOUtilsMaven dependency: http://search.maven.org/#artifactdetails|org.apache.commons|commons-io|1.3.2|jar

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

回答by Sandy D.

The following code is in an AsyncTask:

以下代码位于 AsyncTask 中:

In my background process:

在我的后台进程中:

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

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

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

回答by Nikita Kurtin

I've also encountered with this problem to solve that I've made my own class. Which based on java.net, and supports up to android's API 24 please check it out: HttpRequest.java

我也遇到过这个问题来解决我已经创建了自己的课程。基于 java.net,支持 android 的 API 24 请查看: HttpRequest.java

Using this class you can easily:

使用这个类,您可以轻松地:

  1. Send Http GETrequest
  2. Send Http POSTrequest
  3. Send Http PUTrequest
  4. Send Http DELETE
  5. Send request without extra data params & check response HTTP status code
  6. Add custom HTTP Headersto request (using varargs)
  7. Add data params as Stringquery to request
  8. Add data params as HashMap{key=value}
  9. Accept Response as String
  10. Accept Response as JSONObject
  11. Accept response as byte []Array of bytes (useful for files)
  1. 发送 HttpGET请求
  2. 发送 HttpPOST请求
  3. 发送 HttpPUT请求
  4. 发送 Http DELETE
  5. 发送没有额外数据参数的请求并检查响应 HTTP status code
  6. 添加自定义HTTP Headers请求(使用可变参数)
  7. 添加数据参数作为String查询请求
  8. 添加数据参数为HashMap{key=value}
  9. 接受响应为 String
  10. 接受响应为 JSONObject
  11. 接受响应为byte []字节数组(对文件有用)

and any combination of those - just with one single line of code)

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

Here are a few examples:

这里有一些例子:

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

Example 1:

示例 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();

Example 2:

示例 2

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

Example 3:

示例 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();

Example 4:

示例 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(); 

Example 5:

示例 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

Example 6:

示例 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();

Example 7:

示例 7

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

回答by Frutos Marquez

This is the solution that I have applied to the problem that httpclient deprecated in this version of android 22`

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

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

}

回答by Bali

i had similar issues in using HttpClentand HttpPostmethod since i didn't wanted change my code so i found alternate option in build.gradle(module) file by removing 'rc3' from buildToolsVersion "23.0.1 rc3" and it worked for me. Hope that Helps.

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

回答by Hugo

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...

哪个客户最好?

Apache HTTP 客户端在 Eclair 和 Froyo 上的错误较少。它是这些版本的最佳选择。

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

Reference herefor more info (Android developers blog)

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

回答by Jehy

You are free to continue using HttpClient. Google deprecated only their own version of Apache's components. You can install fresh, powerful and non deprecated version of Apache's HttpClient like I described in this post: https://stackoverflow.com/a/37623038/1727132

您可以继续使用 HttpClient。Google 只弃用了他们自己版本的 Apache 组件。您可以像我在这篇文章中描述的那样安装全新、强大且未弃用的 Apache HttpClient 版本:https: //stackoverflow.com/a/37623038/1727132

回答by Hasan Jamshaid

if targeted for API 22 and older, then should add the following line into build.gradle

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

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

if targeted for API 23 and later, then should add the following line into build.gradle

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

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

If still want to use httpclient library, in Android Marshmallow (sdk 23), you can add:

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

useLibrary 'org.apache.http.legacy'

to build.gradle in the android {} section as a workaround. This seems to be necessary for some of Google's own gms libraries!

android {} 部分中的 build.gradle 作为解决方法。这对于谷歌自己的一些 gms 库来说似乎是必要的!

回答by Keval Choudhary

You can use my easy to use custom class. Just create an object of the abstract class(Anonymous) and define onsuccess() and onfail() method. https://github.com/creativo123/POSTConnection

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