1.加载网络图片
2.http下载文件
3.获取网络地址
第一步:先导入xUtils-2.6.14.jar到libs目录下。
以下主要代码:
package com.example.xutil;
import java.io.File;
import android.app.Activity;
import android.os.Bundle;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.lidroid.xutils.BitmapUtils;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.HttpHandler;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
public class MainActivity extends Activity {
private ImageView testImageView;
private TextView testTextView,testTextView2, textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
testImageView = (ImageView) findViewById(R.id.testImageView);
testTextView = (TextView) findViewById(R.id.testTextView);
testTextView2=(TextView) findViewById(R.id.testTextView2);
textView = (TextView) findViewById(R.id.textView);
// 加载网络图片
//http下载文件
// 获取网络地址
phtot();
httputils();
http();
}
// 加载网络图片
public void phtot() {
BitmapUtils bitmapUtils = new BitmapUtils(this);
// 加载网络图片
bitmapUtils
.display(testImageView,
"http://image63.360doc.com/DownloadImg/2013/08/0712/34328642_45.jpg");
}
//Http下载文件
public void httputils(){
HttpUtils http = new HttpUtils();
HttpHandler handler=http.download("http://image63.360doc.com/DownloadImg/2013/08/0712/34328642_45.jpg","/sdcard/34328642_45.jpg", true,true,new RequestCallBack<File>() {
@Override
public void onStart() {
super.onStart();
testTextView2.setText("conn...");
}
@Override
public void onLoading(long total, long current, boolean isUploading) {
// TODO Auto-generated method stub
super.onLoading(total, current, isUploading);
testTextView2.setText(current + "/" + total);
}
@Override
public void onFailure(HttpException arg0, String arg1) {
testTextView2.setText(arg1);
Toast.makeText(getApplicationContext(), "文件已经存在", 0).show();
}
@Override
public void onSuccess(ResponseInfo<File> arg0) {
testTextView2.setText("downloaded:" + arg0.result.getPath());
Toast.makeText(getApplicationContext(), "下载成功!", 0).show();
}
});
}
// 获取网络地址
public void http() {
HttpUtils http = new HttpUtils();
http.send(HttpRequest.HttpMethod.GET, "http://www.lidroid.com",
new RequestCallBack<String>() {
@Override
public void onLoading(long total, long current,
boolean isUploading) {
testTextView.setText(current + "/" + total);
}
@Override
public void onSuccess(ResponseInfo<String> responseInfo) {
textView.setText(responseInfo.result);
}
@Override
public void onStart() {
}
@Override
public void onFailure(HttpException error, String msg) {
}
});
}
}
xutil的jar,以及源码下载地址:
http://download.csdn.net/detail/wy18370952508/9570352