【问题标题】:Android - Going through the code but not POSTing?Android - 浏览代码但不发布?
【发布时间】:2014-09-21 09:06:00
【问题描述】:

我的编译器通过我的代码没有错误,但它没有发布到网站上?

我已经使用在线网站http://posttestserver.com/data/,它允许我发帖。使用 cURL,我可以发布,但是,当我运行我的代码时它不会发布。

package cdlewis.pebbleaccelstream;

import android.os.AsyncTask;

import java.io.DataOutputStream;
import java.net.HttpURLConnection;
import java.net.URL;


public class PostMethod extends AsyncTask<URL, Void, Void> {

    @Override
    protected Void  doInBackground(URL... url) {


        try {

            HttpURLConnection conn = (HttpURLConnection) url[0].openConnection();
            System.out.println("Connection established");
            conn.setReadTimeout(10000);
            System.out.println("Read timeout");
            conn.setConnectTimeout(15000);
            System.out.println("Connect timeout");
            conn.setRequestMethod("POST");
            System.out.println("Post method");
            conn.setDoInput(true);
            System.out.println("set do input");
            conn.setDoOutput(true);
            System.out.println("set do output");

            DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
            System.out.println("dataoutputstream");
            wr.writeBytes("Hello! ");
            System.out.println("hello");
            wr.flush();
            System.out.println("flush");
            wr.close();
            System.out.println("close");
        } catch (Exception e) {
            System.out.println("Error! ");
        }

    return null;

    }



}

以下是我如何称呼我的班级:-

try {
    new PostMethod().execute(new URL("http://posttestserver.com/data/"));
} catch (MalformedURLException e) {
    e.printStackTrace();
}

它会打印出代码中的所有System.out.println(),但不会在网页上打印任何内容

【问题讨论】:

  • 使用 Volley 库来处理所有这些,来自 Google。它工作得很好,比你的 AsyncTask 更好。它还具有优先级和缓存(等等)。
  • 但为了理智,我想知道为什么它不起作用。

标签: android httpurlconnection android-networking


【解决方案1】:

您只是发送您的请求,而不是检查响应是什么。

int statusCode = conn.getResponseCode();

if (statusCode / 100 == 2) {

    // ok

    // can call conn.getInputStream() now
} else {

    // some error or a redirect

    // in case of error (4xx, 5xx) call conn.getErrorStream()
}

顺便说一句,您不会在 catch 子句中看到太多信息。

【讨论】:

    【解决方案2】:

    System.out.println("close"); 之后添加 连接.connect();错过了。

    【讨论】:

      猜你喜欢
      • 2012-09-22
      • 1970-01-01
      • 1970-01-01
      • 2022-01-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-06
      相关资源
      最近更新 更多