在 android 中是否有推荐的方法来执行 post 请求?

Is there a recommended way of doing post request in android?

在 android 中是否有推荐的方法来执行 post 请求?因为在我使用 HttpPostHttpClient 执行 post 请求之前,这些 类 现在已在 API 级别 22 中弃用。

您可以使用HttpURLConnection

 public  String makeRequest(String pageURL, String params)
{
    String result = null;
    String finalURL =pageURL;
    Logger.i("postURL", finalURL);
    Logger.i("data", params);
    try {
        URL url = new URL(finalURL);
        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setDoOutput(true);
        urlConnection.setDoInput(true);
        urlConnection.setRequestMethod("POST");
        urlConnection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
        urlConnection.setRequestProperty("Accept", "application/json");
        OutputStream os = urlConnection.getOutputStream();
        os.write(params.getBytes("UTF-8"));
        os.close();
        int HttpResultCode =urlConnection.getResponseCode();
        if(HttpResultCode ==HttpURLConnection.HTTP_OK){
            InputStream in = new BufferedInputStream(urlConnection.getInputStream());
            result = convertStreamToString(in);
            Logger.i("API POST RESPONSE",result);
        }else{
            Logger.e("Error in response ", "HTTP Error Code "+HttpResultCode +" : "+urlConnection.getResponseMessage());
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    return result;
}

然后将您的流转换为字符串

 private String convertStreamToString(InputStream is) {
    BufferedReader reader = new BufferedReader(new InputStreamReader(is));
    StringBuilder sb = new StringBuilder();
    String line = null;
    try {
        while ((line = reader.readLine()) != null) {
            sb.append(line).append('\n');
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return sb.toString();
}

创建您的JSON

JSONObject j=new JSONObject();
        try {
            j.put("name","hello");
            j.put("email","hello@gmail.com");
        } catch (JSONException e) {
            e.printStackTrace();
        }

  //Call the method
        makeRequest("www.url.com",j.toString());

是的,它们已被弃用。您可以使用 Volley,Google Dev.

推荐

Volley offers the following benefits: Automatic scheduling of network requests. Multiple concurrent network connections. Transparent disk and memory response caching with standard HTTP cache coherence. Support for request prioritization. Cancellation request API. You can cancel a single request, or you can set blocks or scopes of requests to cancel. Ease of customization, for example, for retry and backoff. Strong ordering that makes it easy to correctly populate your UI with data fetched asynchronously from the network.

Volley 非常容易使用:

// Instantiate the RequestQueue.
RequestQueue queue = Volley.newRequestQueue(this);
String url ="http://www.google.com";

// Request a string response from the provided URL.
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
        new Response.Listener<String>() {
@Override
public void onResponse(String response) {
    // Display the first 500 characters of the response string.
    mTextView.setText("Response is: "+ response.substring(0,500));
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
    mTextView.setText("That didn't work!");
}
});
// Add the request to the RequestQueue.
queue.add(stringRequest);

只是为了展示另一个可能对您有帮助的库:OkHttp

举一个例子 post 来自他们的网站:

public static final MediaType JSON
= MediaType.parse("application/json; charset=utf-8");

OkHttpClient client = new OkHttpClient();

String post(String url, String json) throws IOException {
  RequestBody body = RequestBody.create(JSON, json);
  Request request = new Request.Builder()
      .url(url)
      .post(body)
      .build();
  Response response = client.newCall(request).execute();
  return response.body().string();
}

Retrofit.

你基本上创建了一个接口,其中包含关于其余 API 和你正在调用的参数的注释,并且可以像这样接收解析的 json 模型:

public interface MyService {
    @POST("/api")
    void createTask(@Body CustomObject o, Callback<CustomObject > cb);
}

你也可以同时设置它们,这里有一个指南对我帮助很大:https://futurestud.io/blog/retrofit-getting-started-and-android-client/

尽管这不是 google 文档中推荐的官方方式,但这些都是不错的库,值得一看。