简体   繁体   English

Http在Android中获取请求

[英]Http get request in Android

I need help with sending http get request. 我需要帮助发送http get请求。 Like this: 像这样:

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);

I searched the web but any method I try, the code fails at 'conn.connect();' 我搜索了网络,但我尝试的任何方法,代码都在'conn.connect();'失败了 . Any clues? 有线索吗?

Very hard to tell without the actual error message. 没有实际的错误消息很难分辨。 Random thought: did you add the internet permission to you manifest? 随机想一想:你是否向你的网站添加了互联网权限?

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

If you want some demo code then try following: 如果您想要一些演示代码,请尝试以下操作:

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

and this: 还有这个:

   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();
   }

Hope this helps. 希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM