httpclient
public class MainActivity extends Activity {
Handler handler = new Handler(){
@Override
public void handleMessage (android.os.Message msg) {
Toast.makeText(MainActivity.this , (String)msg.obj, 0 ).show();
}
};
@Override
protected void onCreate (Bundle savedInstanceState) {
super .onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void get (View v){
EditText et_name = (EditText) findViewById(R.id.et_name);
EditText et_pass = (EditText) findViewById(R.id.et_pass);
final String name = et_name.getText().toString();
final String pass = et_pass.getText().toString();
Thread t = new Thread(){
@Override
public void run () {
String path = "http://192.168.13.13/Web/servlet/CheckLogin?name=" + URLEncoder.encode(name) + "&pass=" + pass;
HttpClient hc = new DefaultHttpClient();
HttpGet hg = new HttpGet(path);
try {
HttpResponse hr = hc.execute(hg);
StatusLine sl = hr.getStatusLine();
if (sl.getStatusCode() == 200 ){
HttpEntity he = hr.getEntity();
InputStream is = he.getContent();
String text = Utils.getTextFromStream(is);
Message msg = handler.obtainMessage();
msg.obj = text;
handler.sendMessage(msg);
}
} catch (Exception e) {
e.printStackTrace();
}
}
};
t.start();
}
public void post (View v){
EditText et_name = (EditText) findViewById(R.id.et_name);
EditText et_pass = (EditText) findViewById(R.id.et_pass);
final String name = et_name.getText().toString();
final String pass = et_pass.getText().toString();
Thread t = new Thread(){
@Override
public void run () {
String path = "http://192.168.13.13/Web/servlet/CheckLogin" ;
HttpClient hc = new DefaultHttpClient();
HttpPost hp = new HttpPost(path);
BasicNameValuePair bnvp = new BasicNameValuePair("name" , name);
BasicNameValuePair bnvp2 = new BasicNameValuePair("pass" , pass);
List<BasicNameValuePair> parameters = new ArrayList<BasicNameValuePair>();
parameters.add(bnvp);
parameters.add(bnvp2);
try {
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(parameters, "utf-8" );
hp.setEntity(entity);
HttpResponse hr = hc.execute(hp);
if (hr.getStatusLine().getStatusCode() == 200 ){
InputStream is = hr.getEntity().getContent();
String text = Utils.getTextFromStream(is);
Message msg = handler.obtainMessage();
msg.obj = text;
handler.sendMessage(msg);
}
} catch (Exception e) {
e.printStackTrace();
}
}
};
t.start();
}
}
使用封装好的AsyncHttpClient,从github上面下载这个库
public class MainActivity extends Activity {
@Override
protected void onCreate (Bundle savedInstanceState) {
super .onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void get (View v){
EditText et_name = (EditText) findViewById(R.id.et_name);
EditText et_pass = (EditText) findViewById(R.id.et_pass);
final String name = et_name.getText().toString();
final String pass = et_pass.getText().toString();
String url = "http://192.168.13.13/Web/servlet/CheckLogin?name=" + URLEncoder.encode(name) + "&pass=" + pass;
AsyncHttpClient ahc = new AsyncHttpClient();
ahc.get(url, new MyResponseHandler());
}
public void post (View v){
EditText et_name = (EditText) findViewById(R.id.et_name);
EditText et_pass = (EditText) findViewById(R.id.et_pass);
final String name = et_name.getText().toString();
final String pass = et_pass.getText().toString();
String url = "http://192.168.13.13/Web/servlet/CheckLogin" ;
AsyncHttpClient ahc = new AsyncHttpClient();
RequestParams params = new RequestParams();
params.add("name" , name);
params.add("pass" , pass);
ahc.post(url, params, new MyResponseHandler());
}
class MyResponseHandler extends AsyncHttpResponseHandler{
@Override
public void onSuccess (int statusCode, Header[] headers,
byte [] responseBody) {
Toast.makeText(MainActivity.this , new String(responseBody), 0 ).show();
}
@Override
public void onFailure (int statusCode, Header[] headers,
byte [] responseBody, Throwable error) {
Toast.makeText(MainActivity.this , "请求失败" , 0 ).show();
}
}
}
多线程断点续传下载
public class MainActivity extends Activity {
static int ThreadCount = 3 ;
static int finishedThread = 0 ;
int currentProgress;
String fileName = "QQPlayer.exe" ;
String path = "http://192.168.13.13:8080/" + fileName;
private ProgressBar pb;
TextView tv;
Handler handler = new Handler(){
public void handleMessage (android.os.Message msg) {
tv.setText((long )pb.getProgress() * 100 / pb.getMax() + "%" );
}
};
@Override
protected void onCreate (Bundle savedInstanceState) {
super .onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pb = (ProgressBar) findViewById(R.id.pb);
tv = (TextView) findViewById(R.id.tv);
}
public void click (View v){
Thread t = new Thread(){
@Override
public void run () {
try {
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET" );
conn.setConnectTimeout(5000 );
conn.setReadTimeout(5000 );
if (conn.getResponseCode() == 200 ){
int length = conn.getContentLength();
pb.setMax(length);
File file = new File(Environment.getExternalStorageDirectory(), fileName);
RandomAccessFile raf = new RandomAccessFile(file, "rwd" );
raf.setLength(length);
raf.close();
int size = length / ThreadCount;
for (int i = 0 ; i < ThreadCount; i++) {
int startIndex = i * size;
int endIndex = (i + 1 ) * size - 1 ;
if (i == ThreadCount - 1 ){
endIndex = length - 1 ;
}
new DownLoadThread(startIndex, endIndex, i).start();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
};
t.start();
}
class DownLoadThread extends Thread{
int startIndex;
int endIndex;
int threadId;
public DownLoadThread (int startIndex, int endIndex, int threadId) {
super ();
this .startIndex = startIndex;
this .endIndex = endIndex;
this .threadId = threadId;
}
@Override
public void run () {
try {
File progressFile = new File(Environment.getExternalStorageDirectory(), threadId + ".txt" );
if (progressFile.exists()) {
FileInputStream fis = new FileInputStream(progressFile);
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
int lastProgress = Integer.parseInt(br.readLine());
startIndex += lastProgress;
currentProgress += lastProgress;
pb.setProgress(currentProgress);
handler.sendEmptyMessage(1 );
fis.close();
}
HttpURLConnection conn;
URL url = new URL(path);
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET" );
conn.setConnectTimeout(5000 );
conn.setReadTimeout(5000 );
conn.setRequestProperty("Range" , "bytes=" + startIndex + "-" + endIndex);
if (conn.getResponseCode() == 206 ){
InputStream is = conn.getInputStream();
byte [] b = new byte [1024 ];
int len = 0 ;
int total = 0 ;
File file = new File(Environment.getExternalStorageDirectory(), fileName);
RandomAccessFile raf = new RandomAccessFile(file, "rwd" );
raf.seek(startIndex);
while ((len = is.read(b)) != -1 ){
raf.write(b, 0 , len);
total += len;
currentProgress += len;
pb.setProgress(currentProgress);
handler.sendEmptyMessage(1 );
RandomAccessFile progressRaf = new RandomAccessFile(progressFile, "rwd" );
progressRaf.write((total + "" ).getBytes());
progressRaf.close();
}
raf.close();
finishedThread++;
synchronized (path) {
if (finishedThread == ThreadCount){
for (int i = 0 ; i < ThreadCount; i++) {
File f = new File(Environment.getExternalStorageDirectory(), i + ".txt" );
f.delete();
}
finishedThread = 0 ;
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
<LinearLayout xmlns:android ="http://schemas.android.com/apk/res/android"
xmlns:tools ="http://schemas.android.com/tools"
android:layout_width ="match_parent"
android:layout_height ="match_parent"
android:paddingBottom ="@dimen/activity_vertical_margin"
android:paddingLeft ="@dimen/activity_horizontal_margin"
android:paddingRight ="@dimen/activity_horizontal_margin"
android:paddingTop ="@dimen/activity_vertical_margin"
tools:context =".MainActivity"
android:orientation ="vertical"
>
<Button
android:layout_width ="wrap_content"
android:layout_height ="wrap_content"
android:text ="开始下载"
android:onClick ="click"
/>
<ProgressBar
android:id ="@+id/pb"
android:layout_width ="match_parent"
android:layout_height ="wrap_content"
style ="@android:style/Widget.ProgressBar.Horizontal"
/>
<TextView
android:id ="@+id/tv"
android:layout_width ="wrap_content"
android:layout_height ="wrap_content"
/>
</LinearLayout >
使用xUtils库下载
public class MainActivity extends Activity {
private TextView tv_failure;
private TextView tv_progress;
private ProgressBar pb;
@Override
protected void onCreate (Bundle savedInstanceState) {
super .onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv_failure = (TextView) findViewById(R.id.tv_failure);
tv_progress = (TextView) findViewById(R.id.tv_progress);
pb = (ProgressBar) findViewById(R.id.pb);
}
public void click (View v){
HttpUtils utils = new HttpUtils();
String fileName = "QQPlayer.exe" ;
String path = "http://192.168.13.13:8080/" + fileName;
utils.download(path,
"sdcard/QQPlayer.exe" ,
true ,
true , new RequestCallBack<File>() {
@Override
public void onSuccess (ResponseInfo<File> arg0) {
Toast.makeText(MainActivity.this , arg0.result.getPath(), 0 ).show();
}
@Override
public void onFailure (HttpException arg0, String arg1) {
tv_failure.setText(arg1);
}
@Override
public void onLoading (long total, long current,
boolean isUploading) {
super .onLoading(total, current, isUploading);
pb.setMax((int )total);
pb.setProgress((int )current);
tv_progress.setText(current * 100 / total + "%" );
}
});
}
}