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

pri*_*ank 27 java api android http-post apache-commons-httpclient

目前我使用HttpClient,HttpPost将数据发送到我的PHP serverAndroid app,但所有这些方法是在API 22弃用,在API 23取出,那么有什么替代方案呢?

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

Nik*_*tin 41

我也遇到过这个问题要解决我自己上课的问题.哪个基于java.net,并且最多支持android的API 24请查看: HttpRequest.java

使用此课程,您可以轻松地:

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

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

这里有一些例子:

//Consider next request: 
HttpRequest req=new HttpRequest("http://host:port/path");
Run Code Online (Sandbox Code Playgroud)

例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();
Run Code Online (Sandbox Code Playgroud)

例2:

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

例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();
Run Code Online (Sandbox Code Playgroud)

例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(); 
Run Code Online (Sandbox Code Playgroud)

例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
Run Code Online (Sandbox Code Playgroud)

例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();
Run Code Online (Sandbox Code Playgroud)

例7:

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

  • 如何将文件上传到服务器? (4认同)

fat*_*ddy 28

HttpClient的文档指出你在正确的方向:

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);
Run Code Online (Sandbox Code Playgroud)

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


San*_* D. 7

以下代码位于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();
        }
Run Code Online (Sandbox Code Playgroud)

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