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