android资源文件转url,Android获取指定URL的网页内容

在Java.net.HttpURLConnection该class,可以方便的连接到internet,

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

1.读取指定URL的文本数据 GET /test/test.txt HTTP/1.1

运行效果如下:

httprequestSamperun.bmp

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

httprequestSample-read-image.bmp

指定Project内部资源,利用@drawable/

aa放进去的资源名

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的例子, 在这里就先为大家介绍一下。

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 中应该加入如下节点。

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值