【发布时间】:2015-09-02 03:37:56
【问题描述】:
有没有推荐的方式在 android 中进行发布请求?因为在我使用 HttpPost 和 HttpClient 执行发布请求之前,但这些类现在在 API 级别 22 中已弃用。
【问题讨论】:
-
你可以使用 Volley 或者 UrlConnection manager
有没有推荐的方式在 android 中进行发布请求?因为在我使用 HttpPost 和 HttpClient 执行发布请求之前,但这些类现在在 API 级别 22 中已弃用。
【问题讨论】:
是的,它们已被弃用。您可以使用 Google Dev 推荐的Volley。
Volley 具有以下优势: 网络请求的自动调度。 多个并发网络连接。 具有标准 HTTP 缓存一致性的透明磁盘和内存响应缓存。 支持请求优先级。 取消请求 API。您可以取消单个请求,也可以设置要取消的请求块或范围。 易于定制,例如重试和退避。 强大的排序功能可以轻松地使用从网络异步获取的数据正确填充您的 UI。
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);
【讨论】:
您可以使用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());
【讨论】:
只是为了展示另一个可能对您有所帮助的库:OkHttp
通过他们网站上的示例帖子:
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 文档中推荐的官方方式,但这些都是不错的库,值得一看。
【讨论】: