【问题标题】:Ho do I know if a post request has been successful我知道发帖请求是否成功
【发布时间】:2018-08-06 19:28:20
【问题描述】:

我正在向这个端点http://httpbin.org/post 发出一个帖子请求,它应该返回我所做的帖子,这将是String data = "something to post";,但我不知道这个帖子请求是否成功。我怎样才能知道?

这里是我使用的代码:

public class Post extends AsyncTask <String, String, String>{

    @Override
    protected String doInBackground(String... strings) {
        String urlString = "http://httpbin.org/post"; // URL to call

        Log.d("Blyat", urlString);

        String data = "something to post"; //data to post
        OutputStream out = null;

        try {
            URL url = new URL(urlString);

            Log.d("Post", String.valueOf(url));

            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
            out = new BufferedOutputStream(urlConnection.getOutputStream());

            Log.d("Post", String.valueOf(out));

            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out, "UTF-8"));
            writer.write(data);
            writer.flush();
            writer.close();
            out.close();

            urlConnection.connect();
            Log.d("Post", String.valueOf(urlConnection));

        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
        String algo = "blure";
        return algo;
    }
}

【问题讨论】:

标签: java android httpurlconnection


【解决方案1】:

从 URLConnection 写入 OutputStream 后,您必须检查连接对象的状态代码。

int statusCode = connection.getStatusCode();

如果成功 (== 200),那么您可以通过从 Connection 的 InputStream 获取响应来读取响应。

BufferedReader reader = new BufferedReader(connection.getInputStream());

从响应中你通常会转换成这样的字符串:

        is = connection.getInputStream();
        Writer writer = new StringWriter();
        char[] buffer = new char[1024];
        try {
            Reader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
            int n;
            while ((n = reader.read(buffer)) != -1) {
                writer.write(buffer, 0, n);
            }
        } finally {
            is.close();
        }
        String response =  writer.toString();// have the body from response as String

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-06-16
    • 1970-01-01
    • 1970-01-01
    • 2012-01-20
    • 2011-08-10
    • 2010-11-02
    相关资源
    最近更新 更多