Android - openConnection给出错误

时间:2014-09-21 07:23:09

标签: android android-networking

我尽可能多地尝试我的代码仍然存在错误。我只是想在Android应用程序中执行POST方法。我确实在下面的代码中你会发现资本无效" v"这是因为在我将其作为Void

之前,错误并没有发生
public class PostMethod extends AsyncTask<URL, Void, Void> {


    protected Void doInBackground(URL... url) {


        try {

            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setReadTimeout(10000);
            conn.setConnectTimeout(15000);
            conn.setRequestMethod("POST");
            conn.setDoInput(true);
            conn.setDoOutput(true);
            DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
            wr.writeBytes("Hello! ");
            wr.flush();
            wr.close();

        } catch (Exception e) {
            System.out.println("Error! ");
        }


    }

}

此代码放在我的on create函数中。

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

当前错误:无法识别openConnection()

1 个答案:

答案 0 :(得分:1)

使用

HttpURLConnection conn = (HttpURLConnection) url[0].openConnection();

而不是

 HttpURLConnection conn = (HttpURLConnection) url.openConnection();

beacuse doInBackground参数是Varargs方法参数