Android获取指定URL的网页内容

Android提供的SDK中,利用java.net.HttpURLConnection该class,可以方便的连接到internet,

进行提取GET数据和提交POST数据。


1.读取指定URL的文本数据 GET /test/test.txt HTTP/1.1
运行效果如下:


public class httpRequestSample extends Activity {
/** Called when the activity is first created. */
 @Override
 public void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.main);
 TextView tv = (TextView) findViewById(R.id.TextView01);
tv.setText("just a test");
try { 
URL aURL = new URL("http://192.168.100.65/test/test.txt");
HttpURLConnection conn= (HttpURLConnection)aURL.openConnection();
 conn.connect();
 InputStream is = conn.getInputStream();
 BufferedReader reader = new BufferedReader(new InputStreamReader(is));
。。。

 

 

2.读取画像文件
Android里面显示图片通常利用ImageView的来进行,ImageView可以利用多种资源,project内部的
Res资源,外部的Http资源当然也是OK的。

指定Project内部资源,利用@drawable/
aa放进去的资源名
<ImageView android:id="@+id/imgv2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/aa" />
通过读取Http的图像资源来获取
URL aURL = new URL("http://your-server/imagexxx.jpg");
URLConnection conn = aURL.openConnection();
 conn.connect();
 InputStream is = conn.getInputStream();
 BufferedInputStream bis = new BufferedInputStream(is);
 bm = BitmapFactory.decodeStream(bis);
 bis.close();
 is.close();
 iv.setImageBitmap(bm);

 

 

网络上很多关于Android HttpURLConnection的例子, 在这里就先为大家介绍一下。

 
 
  1. void getInput(){   
  2. try  
  3. {  
  4. URL url = new URL("http://www.google.cn/");  
  5. HttpURLConnection conn = (HttpURLConnection) url.openConnection();  
  6. conn.setDoInput(true);  
  7. conn.setConnectTimeout(10000);  
  8. conn.setRequestMethod("GET");  
  9. conn.setRequestProperty("accept", "*/*");  
  10. String location = conn.getRequestProperty("location");  
  11. int resCode = conn.getResponseCode();  
  12. conn.connect();  
  13. InputStream stream = conn.getInputStream();  
  14. byte[] data=new byte[102400];  
  15. int length=stream.read(data);  
  16. String str=new String(data,0,length);   
  17. conn.disconnect();  
  18. System.out.println(str);  
  19. stream.close();  
  20. }  
  21. catch(Exception ee)  
  22. {  
  23. System.out.print("ee:"+ee.getMessage());   
  24. }  

只是要注意的是配置一个权限,AndroidManifest.xml 中应该加入如下节点。

 
 
  1. < /activity> 
  2. < /application> 
  3. < uses-permission android:name="android.permission.INTERNET"> 
  4. < /uses-permission> 
  5. < /manifest>  

可以把AndroidManifest.xml open with manifest editor 来编辑 在permissions中add uses-permission,然后再在name中选择Android.permission.INTERNET,然后save就ok了。

  • 1
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值