分享

Android获取指定URL的网页内容

 gearss 2016-06-08

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了。

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多