利用HttpClient URLConnection两个类 访问服务器

利用HttpClient类访问图片


//所有网络访问代码都要写在工作线程中

new Thread(){
public void run() {

                //创建HttpClient对象
HttpClient client=new DefaultHttpClient();

//声明网络访问的方式GET
HttpGet get=new HttpGet("http://172.60.10.123:8080/ems/getCode.do");//172.60.10.123指本机的IP
try {

//发起网络访问,获得服务器响应
HttpResponse resp = client.execute(get);

//解析服务器返回的具体内容
HttpEntity entity = resp.getEntity();
InputStream is=entity.getContent();
Bitmap bitmap=BitmapFactory.decodeStream(is);

//通过Message将结果从工作线程提交到主线程
Message.obtain(handler, 101, bitmap).sendToTarget();
} catch (Exception e) {
e.printStackTrace();
}

};
}.start();

然后在主线程中利用handler处理消息即可


利用HttpClient访问网页


new Thread(){
public void run() {
try {
HttpClient client=new DefaultHttpClient();
HttpGet get=new HttpGet("http://172.60.10.123:8080/ems/login.html");
HttpResponse resp=client.execute(get);
HttpEntity entity = resp.getEntity();
InputStream is = entity.getContent();
//Bitmap bitmap = BitmapFactory.decodeStream(is);
BufferedReader br=new BufferedReader(new InputStreamReader(is));
String line=null;
StringBuilder sb=new StringBuilder();
while((line=br.readLine())!=null){
sb.append(line);
}
br.close();
Message.obtain(handler, 102,sb.toString()).sendToTarget();
} catch (Exception e) {
e.printStackTrace();
}
};
}.start();

然后在主线程用handler处理消息即可



利用URLConnection访问图片

new Thread(){
public void run() {
try {
URL url=new URL("http://172.60.10.123:8080/ems/getCode.do");
URLConnection connection = url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream is=connection.getInputStream();
Bitmap bitmap=BitmapFactory.decodeStream(is);
Message.obtain(handler, 101, bitmap).sendToTarget();
} catch (Exception e) {
e.printStackTrace();
}
};
}.start();

主线程处理消息


利用URLConnection访问网页


new Thread(){
public void run() {
try {
URL url=new URL("http://172.60.10.123:8080/ems/login.html");
URLConnection connection = url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream is = connection.getInputStream();
BufferedReader br=new BufferedReader(new InputStreamReader(is));
String line=null;
StringBuilder sb=new StringBuilder();
while((line=br.readLine())!=null){
sb.append(line);
}
Message.obtain(handler, 102, sb.toString()).sendToTarget();
} catch (Exception e) {
e.printStackTrace();
}
};
}.start();


然后在主线程处理消息


使用这两种类访问服务器时都要注意添加权限:

<uses-permission android:name="android.permission.INTERNET"/>



服务器使用的是tomcat


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值