有没有推荐的方法在Android中做post post请求?

时间:2015-06-17 04:44:20

标签: android http-post

有没有推荐的方法在android中进行发布请求?因为在我使用HttpClientclass ExtendedLoginForm(LoginForm): name = TextField('User Name:', [Required()]) del LoginForm.email security = Security(app, user_datastore, login_form=ExtendedLoginForm) 执行post请求之前,这些类现在已在API级别22中弃用。

3 个答案:

答案 0 :(得分:0)

您可以使用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());

答案 1 :(得分:0)

是的,他们被弃用了。您可以使用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);

答案 2 :(得分:0)

只是为了展示另一个可以帮助您的库: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/

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

相关问题