网络上很多关于httpUrlconnection的例子,
void getInput(){
try
{
URL url = new URL("http://www.google.cn/");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true);
conn.setConnectTimeout(10000);
conn.setRequestMethod("GET");
conn.setRequestProperty("accept", "*/*");
String location = conn.getRequestProperty("location");
int resCode = conn.getResponseCode();
conn.connect();
InputStream stream = conn.getInputStream();
byte[] data=new byte[102400];
int length=stream.read(data);
String str=new String(data,0,length);
conn.disconnect();
System.out.println(str);
stream.close();
}
catch(Exception ee)
{
System.out.print("ee:"+ee.getMessage());
}
}
只是要注意的是配置一个权限,AndroidManifest.xml 中应该加入如下节点。
</activity>
</application>
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
</manifest>
可以把AndroidManifest.xml open with manifest editor 来编辑 在permissions中add uses-permission,然后再在name中选择android.permission.INTERNET,然后save就ok了。