Http在Android中获取请求

时间:2011-01-08 13:20:02

标签: android http request

我需要帮助发送http get请求。像这样:

URL connectURL;
connectURL = new URL(address);
HttpURLConnection conn = (HttpURLConnection)connectURL.openConnection(); 
// do some setup
conn.setDoInput(true); 
conn.setDoOutput(true); 
conn.setUseCaches(false); 
conn.setRequestMethod("GET"); 
// connect and flush the request out
conn.connect();
conn.getOutputStream().flush();
// now fetch the results
String response = getResponse(conn);
et.setText(response);

我在网上搜索但是我尝试的任何方法,代码都在'conn.connect();'失败了。有线索吗?

2 个答案:

答案 0 :(得分:4)

如果没有实际的错误消息,很难说清楚。随机想一想:你是否向你提供了互联网许可证?

 <uses-permission android:name="android.permission.INTERNET"/> 

答案 1 :(得分:3)

如果您想要一些demo code,请尝试以下操作:

 URL url = new URL("url.com");
   HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
   try {
     InputStream in = new BufferedInputStream(urlConnection.getInputStream());
     readStream(in);
   } finally {
     urlConnection.disconnect();
   }

和此:

   HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
   try {
     urlConnection.setDoOutput(true);
     urlConnection.setChunkedStreamingMode(0);

     OutputStream out = new BufferedOutputStream(urlConnection.getOutputStream());
     writeStream(out);

     InputStream in = new BufferedInputStream(urlConnection.getInputStream());
     readStream(in);
   } finally {
     urlConnection.disconnect();
   }

希望这有帮助。