实现方式 :
1)JAVA中 UrlConnection类的派生类HttpUrlConnection
2)Apache下的HttpClient
3) 第三方框架,常用的第三方框架有xUtils的HttpUtils 、AsyncHttpClient
HttpUtils 中用到两个方法send()和download()
AsyncHttpClient方法用到:
BitmapUtils bmpUtils = new BitmapUtils(this) ;bmpUtils.display(iv, imgUrl) ;
操作步骤 :
1)初始化请求对象
2)设置请求参数
3)网络发送请求
4)获取响应结果:判断结果码是否是200,如果是则请求成功获取
Android 网络操作注意:
1. 添加权限 Internet权限,如果第三方网络操作框架还需要WRITE_EXTERNEL_STORAGE
2. 网络请求必须单独开启线程
在这个过程中遇到的问题:网络请求结果处理:
网络请求必须单独开启线程,网络请求结果通过控件显示,但android规定非UI主线程不能更新控件外观。
解决方案:
1)通过Broadcast解决
2)通过Handler发送消息解决
handler = new Handler(){
// 回调方法,每当handler收到消息Message时,自动调用该方法
public void handleMessage(Message msg) {
switch(msg.what) {
}
};
} ;
Message 的初始化 Message.obtain()
四个属性 :
what 用来标识消息类型
以下三个属性用来传递消息中
数据
Int arg1 , arg2
Object obj
1.JAVA中UrlConnection类的派生类HttpUrlConnection(建立网络连接的一个类)
/**
* 网络请求结果:
* 一种是需要字符串 String s = new String(byte[])
* 一种是需要byte[]
*
*/
public class NetUrlConnection {
public static byte[] request(String strUrl){
byte[] result = null ;
HttpURLConnection conn = null;
try {
URL url = new URL(strUrl);
conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5*1000);
conn.setReadTimeout(5*1000);
conn.connect();
if(200==conn.getResponseCode()){
InputStream in = conn.getInputStream();
//将输入字节流转换
ByteArrayOutputStream bytearray =new ByteArrayOutputStream();
byte [] buffer = new byte[4*1024] ;
int len;
while(-1 != (len = in.read(buffer))){
bytearray.write(buffer, 0, len);
}
//最后将结果转换为字节数组
result = bytearray.toByteArray();
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
if(conn!=null ){
conn.disconnect();
}
}
return result;
}
}
非UI主线程不能更新控件外观,通过Broadcast(广播)方式处理网络请求结果:
public class MainActivity extends Activity implements OnClickListener {
TextView text;
ImageView images;
String imgurl = "http://img2.duitang.com/uploads/item/201112/18/20111218201622_4LnZS.thumb.600_0.jpg";
String texturl = "http://api.map.baidu.com/telematics/v3/weather?output=json&ak=wwaIKGCMI1n4teVrz5GjRq57&location=%E5%A4%A9%E6%B4%A5";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
resister();
setContentView(R.layout.activity_main);
images = (ImageView) findViewById(R.id.img);
text = (TextView) findViewById(R.id.text);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_img:
new Thread() {
public void run() {
byte[] r1 = NetUrlConnection.request(imgurl);
Intent bcIntent = new Intent();
bcIntent.putExtra("result", r1);
bcIntent.setAction("com.example.img");
sendBroadcast(bcIntent);
};
}.start();
break;
case R.id.btn_text:
new Thread() {
public void run() {
byte[] r2 = NetUrlConnection.request(texturl);
Intent bcIntent = new Intent();
bcIntent.putExtra("result", r2);
bcIntent.setAction("com.example.text");
sendBroadcast(bcIntent);
};
}.start();
break;
}
}
class Mybroad extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equals("com.example.img")) {
byte[] r1 = intent.getByteArrayExtra("result");
// 把字节数组转换成图片
Bitmap bmp = BitmapFactory.decodeByteArray(r1, 0, r1.length);
images.setImageBitmap(bmp);
}
if (action.equals("com.example.text")) {
byte[] r2 = intent.getByteArrayExtra("result");
String txt = new String(r2);
text.setText(txt);
}
}
}
2.Apache下的HttpClient
public class HttpClientConnection {
public static byte[] conn(String urlStr) {
byte[] result = null ;
// 1.
HttpClient client = new DefaultHttpClient() ;
// 2.
HttpParams params = new BasicHttpParams() ;
HttpConnectionParams.setConnectionTimeout(params, 5 * 1000) ;
HttpConnectionParams.setSoTimeout(params, 5 * 1000) ;
// 3.
HttpGet request = new HttpGet(urlStr) ;
// HttpPost request = new HttpPost(urlStr) ;
try {
HttpResponse response = client.execute(request) ;
// 4.
if(200 == response.getStatusLine().getStatusCode()) {
HttpEntity entity = response.getEntity() ;
result = EntityUtils.toByteArray(entity) ;
}
} catch (Exception e) {
e.printStackTrace();
}
return result ;
}
}
非UI主线程不能更新控件外观,通过Handler机制处理网络请求结果:
public class SecondActivity extends Activity implements OnClickListener {
private ImageView iv;
private TextView tv;
private String imgUrl = "http://img2.duitang.com/uploads/item/201112/18/20111218201622_4LnZS.thumb.600_0.jpg";
private String txtUrl = "http://api.map.baidu.com/telematics/v3/weather?output=json&ak=wwaIKGCMI1n4teVrz5GjRq57&location=%E5%A4%A9%E6%B4%A5";
private Handler handler ;
private ProgressDialog pDialog ;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.btn_second).setVisibility(View.GONE) ;
iv = (ImageView) findViewById(R.id.iv);
tv = (TextView) findViewById(R.id.tv);
pDialog = new ProgressDialog(this);
initHandler() ;
}
private void initHandler() {
handler = new Handler(){
// 回调方法,每当handler收到消息Message时,自动调用该方法
public void handleMessage(Message msg) {
switch(msg.what) {
case WHAT_IMG :
pDialog.dismiss();
byte[] r1 = (byte[]) msg.obj ;
Bitmap bmp = BitmapFactory.decodeByteArray(r1, 0, r1.length);
iv.setImageBitmap(bmp);
break ;
case WHAT_TXT :
pDialog.dismiss();
byte[] r2 = (byte[]) msg.obj ;
String txt = new String(r2);
tv.setText(txt);
break;
}
};
} ;
}
final int WHAT_IMG = 1 ;
final int WHAT_TXT = 2 ;
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_img:
pDialog.show() ;
new Thread() {
public void run() {
byte[] r1 = HttpClientConnection.conn(imgUrl);
// 发消息
Message msg = Message.obtain() ;
msg.what = WHAT_IMG ;
msg.obj = r1;
handler.sendMessage(msg) ;
};
}.start();
break;
case R.id.btn_txt:
pDialog.show() ;
new Thread() {
public void run() {
byte[] r2 = HttpClientConnection.conn(txtUrl);
Message msg = Message.obtain() ;
msg.what = WHAT_TXT ;
msg.obj = r2 ;
handler.sendMessage(msg) ;
};
}.start();
break;
}
}
}
3,这里介绍HttpUtils框架
使用此框架时,如果显示图片只需要执行以下两句
// ImageView 显示网络图片//
BitmapUtils bmpUtils = new BitmapUtils(this) ;//
bmpUtils.display(iv, imgUrl) ;
GET方式:
httpUtis.send(
HttpMethods.GET ,
url ,
RequestCallBack<T>
) ;
POST方式:
httpUtis.send(
HttpMethods.POST ,
url ,
params ,
RequestCallBack<T>
) ;
关于参数设置:
RequestParams params = new RequestParams();
params.addQueryStringParameter("name", "value");
// addQueryStringParameter将参数添加到url末尾,该参数被web端get方式接收
params.addBodyParameter("name", "value");
// addBodyParameter将参数设置为post方式所需上传参数,该参数被web端post方式接收
更多介绍查看1417Demo,Stock项目
以练习的代码(来自压缩包0904.zip)public class ThirdActivity extends Activity implements OnClickListener {
private ImageView iv;
private TextView tv;
private String imgUrl = "http://img2.duitang.com/uploads/item/201112/18/20111218201622_4LnZS.thumb.600_0.jpg";
private String txtUrl = "http://api.map.baidu.com/telematics/v3/weather?output=json&ak=wwaIKGCMI1n4teVrz5GjRq57&location=%E5%A4%A9%E6%B4%A5";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.btn_second).setVisibility(View.GONE);
findViewById(R.id.btn_third).setVisibility(View.GONE);
iv = (ImageView) findViewById(R.id.iv);
tv = (TextView) findViewById(R.id.tv);
// ImageView 显示网络图片
// BitmapUtils bmpUtils = new BitmapUtils(this) ;
// bmpUtils.display(iv, imgUrl) ;
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_img:
downImg();
break;
case R.id.btn_txt:
downTxt();
break;
}
}
private void downTxt() {
HttpUtils http = new HttpUtils();
http.send(HttpRequest.HttpMethod.GET, txtUrl,
new RequestCallBack<String>() {
@Override
public void onSuccess(ResponseInfo<String> responseInfo) {
String txt = responseInfo.result;
tv.setText(txt);
}
@Override
public void onFailure(HttpException error, String msg) {
Toast.makeText(ThirdActivity.this, "下载文本失败!",
Toast.LENGTH_LONG).show();
}
});
}
private void downImg() {
String target = getExternalCacheDir().getAbsolutePath() + "/"
+ "temp.jpg";
HttpUtils http = new HttpUtils();
http.download(imgUrl, target, true, new RequestCallBack<File>() {
@Override
public void onSuccess(ResponseInfo<File> responseInfo) {
File f = responseInfo.result;
Log.v("thirdActivity", f.getAbsolutePath());
Bitmap bmp = BitmapFactory.decodeFile(f.getAbsolutePath());
iv.setImageBitmap(bmp);
}
@Override
public void onFailure(HttpException error, String msg) {
Log.v("thirdActivity", error.getMessage() + "|" + msg);
Toast.makeText(ThirdActivity.this, "下载图片失败!", Toast.LENGTH_LONG)
.show();
}
});
}
}