Android Http连接

时间:2015-02-25 21:12:57

标签: android http

我尝试连接到一个url,一个简单因为我想连接到服务器之后。为此,我有

String urlServer = "http://www.google.com";
URL url = new URL(urlServer);
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
connection.setRequestMethod("POST");
outputStream = new DataOutputStream( connection.getOutputStream() );

最后一行转到catch异常。我不知道会发生什么,我也试过这个

Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("10.0.0.1", 8080));
conn = new URL(urlString).openConnection(proxy);

它给了我

  

LogCat给了我

android.os.NetworkOnMainThreadException

1 个答案:

答案 0 :(得分:0)

将您的代码放入asynctask ......

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

    @Override
    protected String doInBackground(String... params) {
        // TODO Auto-generated method stub
        return null;
    }

}

只需将与网络相关的行放在doInBackground中。