Android Httpurlconnection问题 - .connect之后没有任何反应

时间:2017-11-25 18:03:13

标签: android httpurlconnection

我是Android开发方面的新手,我遇到了一个奇怪的问题。

以下代码应该有效:

URL url = new URL("http://127.0.0.1/test.html");
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("GET");
connection.connect();

int code = connection.getResponseCode();  
System.out.println("code: "+code);

问题是,在我执行connection.connect()之后;没有任何反应,即使我在连接后添加了一个textX.setText(),我也无法做任何动作。

知道可能是什么问题吗?

这是我的整个方法,我所要做的就是从API中获取一些文字,其中包含" OK"实际上,但我无法使其发挥作用。

public void conn (View view)
    {
        TextView text2 = (TextView)findViewById(R.id.text2);
        text2.setText("connecting...");
        String output="";
        //All working until here
        URL url;
        HttpURLConnection urlConnection = null;
        try {
            output="about to connect";
            text2.setText(output);
            url = new URL("http://127.0.0.1:4444/localweb/api/api.php");

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

            connection.setRequestMethod("GET");
            connection.connect();
            InputStream in = urlConnection.getInputStream();
            text2.append("\nabout to get code");
            int code = connection.getResponseCode();
            text2.setText(Integer.toString(code));

            //urlConnection = (HttpURLConnection) url.openConnection();
            //urlConnection.connect();
            //output=urlConnection.getResponseMessage();
            //text2.setText(output);


            InputStreamReader isw = new InputStreamReader(in);

            int data = isw.read();
            while (data != -1) {
                char current = (char) data;
                data = isw.read();
                System.out.print(current);
                output=output+current;
            }
            //text2.setText(output);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (urlConnection != null) {
                urlConnection.disconnect();
            }
        }
    }

0 个答案:

没有答案