利用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