1.get和post从服务端请求数据
public class MainActivity extends Activity {
private EditText et_username;
private EditText et_password;
private String path = "http://192.168.43.21:8080/login";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et_username = (EditText) findViewById(R.id.et_username);
et_password = (EditText) findViewById(R.id.et_password);
}
public void login(final View view){
new Thread(){
public void run() {
String username = et_username.getText().toString();
String password = et_password.getText().toString();
try {
if(view.getId() == R.id.btn_login){
String spec = path + "?username=" +
URLEncoder.encode(username, "utf-8") + "&password=" +
URLEncoder.encode(password,"utf-8");
URL url = new URL(spec);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setConnectTimeout(10000);
int code = connection.getResponseCode();
if(code == 200){
String result = Utils.getStringFromStream(connection.getInputStream());
showToast(result);
}
}else if(view.getId() == R.id.btn_loginToPost){
String params = "username=" +
URLEncoder.encode(username, "utf-8") + "&password=" +
URLEncoder.encode(password,"utf-8");
URL url = new URL(path);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setConnectTimeout(10000);
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestProperty("Content-Length", String.valueOf(params.length()));
connection.setDoOutput(true);
connection.getOutputStream().write(params.getBytes());
int code = connection.getResponseCode();
if(code == 200){
String result = Utils.getStringFromStream(connection.getInputStream());
showToast(result);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}.start();
}
private void showToast(final String str){
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(getApplicationContext(), str, Toast.LENGTH_SHORT).show();
}
});
}
}
2.使用HttpClient进行get和post访问数据
public class MainActivity extends Activity {
private String path = "http://192.168.43.21:8080/login";
private EditText et_username;
private EditText et_password;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et_username = (EditText) findViewById(R.id.et_username);
et_password = (EditText) findViewById(R.id.et_password);
Button btn_login = (Button) findViewById(R.id.btn_login);
btn_login.setOnClickListener(new MyListener());
Button btn_loginPost = (Button) findViewById(R.id.btn_loginPost);
btn_loginPost.setOnClickListener(new MyListener());
}
private class MyListener implements OnClickListener {
@Override
public void onClick(View v) {
if(v.getId() == R.id.btn_login){
new Thread(){
@Override
public void run() {
System.out.println("kk");
String username = et_username.getText().toString();
String password = et_password.getText().toString();
String uri = path + "?username=" + username + "&password=" + password;
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(uri);
System.out.println(uri);
try {
HttpResponse httpResponse = httpClient.execute(httpGet);
StatusLine statusLine = httpResponse.getStatusLine();
int code = statusLine.getStatusCode();
if(code == 200){
HttpEntity entity = httpResponse.getEntity();
InputStream inputStream = entity.getContent();
String result = Utils.getStringFromStream(inputStream);
showToast(result);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}.start();
}else if(v.getId() == R.id.btn_loginPost){
new Thread(){
public void run() {
System.out.println("post");
String username = et_username.getText().toString();
String password = et_password.getText().toString();
BasicNameValuePair valuePair1 = new BasicNameValuePair("username",username);
BasicNameValuePair valuePair2 = new BasicNameValuePair("password", password);
List<BasicNameValuePair> list = new ArrayList<BasicNameValuePair>();
list.add(valuePair1);
list.add(valuePair2);
try {
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(list,"utf-8");
HttpPost httpPost = new HttpPost(path);
httpPost.setEntity(formEntity);
DefaultHttpClient defaultHttpClient = new DefaultHttpClient();
HttpResponse httpResponse = defaultHttpClient.execute(httpPost);
int code = httpResponse.getStatusLine().getStatusCode();
if(code == 200){
HttpEntity entity = httpResponse.getEntity();
InputStream inputStream = entity.getContent();
String result = Utils.getStringFromStream(inputStream);
showToast(result);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}.start();
}
}
}
private void showToast(final String str){
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(getApplicationContext(), str, Toast.LENGTH_SHORT).show();
}
});
}
}
3.使用第三方框架进行get和post请求
public class MainActivity extends Activity {
private String path = "http://192.168.43.21:8080/login";
private EditText et_password;
private EditText et_username;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et_username = (EditText) findViewById(R.id.et_username);
et_password = (EditText) findViewById(R.id.et_password);
Button btn_login = (Button) findViewById(R.id.btn_login);
btn_login.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
System.out.println("get--");
String username = et_username.getText().toString();
String password = et_password.getText().toString();
String url = path + "?username=" + username + "&password=" + password;
AsyncHttpClient httpClient = new AsyncHttpClient();
httpClient.get(url, new AsyncHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
if(statusCode == 200){
try {
showToast(new String(responseBody,"utf-8"));
} catch (Exception e) {
e.printStackTrace();
}
}
}
@Override
public void onFailure(int statusCode, Header[] headers,
byte[] responseBody, Throwable error) {
}
});
}
});
Button btn_loginPost = (Button) findViewById(R.id.btn_loginPost);
btn_loginPost.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
System.out.println("post--");
String username = et_username.getText().toString();
String password = et_password.getText().toString();
AsyncHttpClient httpClient = new AsyncHttpClient();
Map<String,String> map = new HashMap<String,String>();
map.put("username", username);
map.put("password", password);
RequestParams requestParams = new RequestParams(map);
httpClient.post(path, requestParams, new AsyncHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
if(statusCode == 200){
try {
showToast(new String(responseBody,"utf-8"));
} catch (Exception e) {
e.printStackTrace();
}
}
}
@Override
public void onFailure(int statusCode, Header[] headers,
byte[] responseBody, Throwable error) {
}
});
}
});
}
private void showToast(final String str){
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(getApplicationContext(), str, Toast.LENGTH_SHORT).show();
}
});
}
}
4.多线程下载
1:突破服务端对单个线程速度的限制。
2:无法突破带宽的限制。
5.多线程下载原理代码
public class MainMoreThread {
public static void main(String[] args) {
String path = "http://127.0.0.1:8080/img/news.xml";
try {
URL url = new URL(path);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setConnectTimeout(10000);
connection.setRequestProperty("Range", "bytes=0-20");
if(connection.getResponseCode() == 206){
InputStream inputStream = connection.getInputStream();
String result = Utils.getStringFromStream(inputStream);
System.out.println(result);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
6.多线程下载代码
public class MoreThreadDownload {
private static String spec = "http://127.0.0.1:8080/img/news.xml";
private static int threadCount = 3;
public static void main(String[] args) {
try {
URL url = new URL(spec);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setConnectTimeout(10000);
int responseCode = connection.getResponseCode();
if(responseCode == 200){
int length = connection.getContentLength();
RandomAccessFile raf = new RandomAccessFile(getFileName(spec), "rw");
raf.setLength(length);
for(int i = 0;i < threadCount;i++){
int n = length / threadCount;
int start = i * n;
int end = (i + 1) * n - 1;
if(i == threadCount){
end = length - 1;
}
new DownloadThread(start, end, i).start();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
private static class DownloadThread extends Thread {
private int startIndex;
private int endIndex;
private int threadId;
public DownloadThread(int startIndex, int endIndex, int threadId) {
super();
this.startIndex = startIndex;
this.endIndex = endIndex;
this.threadId = threadId;
}
public void run() {
try {
URL url = new URL(spec);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setReadTimeout(10000);
connection.setRequestProperty("Range", "bytes=" + startIndex + "-" + endIndex);
if(connection.getResponseCode() == 206){
System.out.println("文件开始下载" + threadId + "-" + startIndex + "-" + endIndex);
InputStream inputStream = connection.getInputStream();
RandomAccessFile raf = new RandomAccessFile(getFileName(spec), "rw");
raf.seek(startIndex);
int len = 0;
byte[] bytes = new byte[1024];
while((len = inputStream.read(bytes)) != -1){
raf.write(bytes,0,len);
}
raf.close();
System.out.println("下载结束");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
public static String getFileName(String spec){
String[] strs = spec.split("/");
return strs[strs.length - 1];
}
}
7.断点续传
public class MoreThreadDownload {
private static String spec = "http://127.0.0.1:8080/img/news.xml";
private static int threadCount = 3;
public static void main(String[] args) {
try {
URL url = new URL(spec);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setConnectTimeout(10000);
int responseCode = connection.getResponseCode();
if(responseCode == 200){
int length = connection.getContentLength();
RandomAccessFile raf = new RandomAccessFile(getFileName(spec), "rw");
raf.setLength(length);
for(int i = 0;i < threadCount;i++){
int n = length / threadCount;
int start = i * n;
int end = (i + 1) * n - 1;
if(i == threadCount){
end = length - 1;
}
new DownloadThread(start, end, i).start();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
private static class DownloadThread extends Thread {
private int startIndex;
private int endIndex;
private int threadId;
public DownloadThread(int startIndex, int endIndex, int threadId) {
super();
this.startIndex = startIndex;
this.endIndex = endIndex;
this.threadId = threadId;
}
public void run() {
try {
File f = new File(getFileName(spec) + threadId + ".log");
if(f != null && f.length() > 0){
System.out.println("11111");
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(f)));
String line = br.readLine();
startIndex = Integer.parseInt(line);
}
URL url = new URL(spec);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setReadTimeout(10000);
connection.setRequestProperty("Range", "bytes=" + startIndex + "-" + endIndex);
if(connection.getResponseCode() == 206){
System.out.println("文件开始下载" + threadId + "-" + startIndex + "-" + endIndex);
InputStream inputStream = connection.getInputStream();
RandomAccessFile raf = new RandomAccessFile(getFileName(spec), "rw");
raf.seek(startIndex);
int len = 0;
byte[] bytes = new byte[1024];
int count = 0;
while((len = inputStream.read(bytes)) != -1){
raf.write(bytes,0,len);
count += len;
int position = startIndex + count;
RandomAccessFile file = new RandomAccessFile(getFileName(spec) + threadId +
".log", "rwd");
file.write(String.valueOf(position).getBytes());
}
raf.close();
System.out.println("下载结束");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
public static String getFileName(String spec){
String[] strs = spec.split("/");
return strs[strs.length - 1];
}
}
8.Android完成多线程下载和断点续传
public class MainActivity extends Activity implements OnClickListener {
private EditText ed_url;
private EditText ed_threadCount;
private Button btn_download;
private LinearLayout ll_progess;
private String spec = "http://10.0.2.2:8080/img/news.xml";
private int threadCount = 3;
private int n;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ed_url = (EditText) findViewById(R.id.et_url);
ed_threadCount = (EditText) findViewById(R.id.et_threadCount);
btn_download = (Button) findViewById(R.id.btn_download);
ll_progess = (LinearLayout) findViewById(R.id.ll_progress);
btn_download.setOnClickListener(this);
}
@Override
public void onClick(View v) {
ll_progess.removeAllViews();
String temp = ed_threadCount.getText().toString().trim();
threadCount = Integer.parseInt(temp);
for(int i = 0;i < threadCount;i++){
View.inflate(getApplicationContext(), R.layout.item, ll_progess);
}
new Thread(){
public void run() {
try {
URL url = new URL(spec);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setConnectTimeout(10000);
int responseCode = connection.getResponseCode();
if(responseCode == 200){
int length = connection.getContentLength();
RandomAccessFile raf = new RandomAccessFile(getFileName(spec), "rw");
raf.setLength(length);
for(int i = 0;i < threadCount;i++){
n = length / threadCount;
int start = i * n;
int end = (i + 1) * n - 1;
if(i == threadCount){
end = length - 1;
}
ProgressBar progressBar = (ProgressBar) ll_progess.getChildAt(i);
progressBar.setMax(end - start);
new DownloadThread(start, end, i).start();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}.start();
}
private class DownloadThread extends Thread {
private int startIndex;
private int endIndex;
private int threadId;
private ProgressBar progressBar;
public DownloadThread(int startIndex, int endIndex, int threadId) {
this.startIndex = startIndex;
this.endIndex = endIndex;
this.threadId = threadId;
progressBar = (ProgressBar) ll_progess.getChildAt(threadId);
}
public void run() {
try {
File f = new File(getFileName(spec) + threadId + ".log");
if(f != null && f.length() > 0){
System.out.println("11111");
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(f)));
String line = br.readLine();
startIndex = Integer.parseInt(line);
}
URL url = new URL(spec);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setReadTimeout(10000);
connection.setRequestProperty("Range", "bytes=" + startIndex + "-" + endIndex);
if(connection.getResponseCode() == 206){
InputStream inputStream = connection.getInputStream();
RandomAccessFile raf = new RandomAccessFile(getFileName(spec), "rw");
raf.seek(startIndex);
int len = 0;
byte[] bytes = new byte[1024];
int count = 0;
while((len = inputStream.read(bytes)) != -1){
raf.write(bytes,0,len);
count += len;
int position = startIndex + count;
RandomAccessFile file = new RandomAccessFile(getFileName(spec) + threadId +
".log", "rwd");
file.write(String.valueOf(position).getBytes());
progressBar.setProgress(position - threadId * n);
}
raf.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
public String getFileName(String spec){
String[] strs = spec.split("/");
return getCacheDir().getAbsolutePath() + "/" + strs[strs.length - 1];
}
}
<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:orientation="vertical"
tools:context=".MainActivity" >
<EditText
android:id="@+id/et_url"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="请输入url" />
<EditText
android:id="@+id/et_threadCount"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="请输入线程数" />
<Button
android:id="@+id/btn_download"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="click"
android:text="下载" />
<LinearLayout
android:id="@+id/ll_progress"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
</LinearLayout>
</LinearLayout>
<?xml version="1.0" encoding="utf-8"?>
<ProgressBar xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
style="@android:style/Widget.ProgressBar.Horizontal" >
</ProgressBar>
9.使用开源项目实现文件上传
public class MainActivity extends Activity {
private ProgressBar pb;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btn_download = (Button) findViewById(R.id.btn_download);
pb = (ProgressBar) findViewById(R.id.pb);
btn_download.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
HttpUtils httpUtils = new HttpUtils();
String url = "http://10.0.2.2:8080/img/news.xml";
httpUtils.download(url, getFileName(url), true,new RequestCallBack<File>() {
@Override
public void onSuccess(ResponseInfo<File> responseInfo) {
}
@Override
public void onFailure(HttpException error, String msg) {
}
@Override
public void onLoading(long total, long current,
boolean isUploading) {
pb.setMax((int)total);
pb.setProgress((int)current);
}
});
}
});
}
private String getFileName(String path) {
String[] result = path.split("/");
return getCacheDir().getAbsolutePath()+"/"+result[result.length-1];
}
}
10.getApplicationContext()
1:getApplicationContext()的获取应用的应用的上下文,生命周期比较长,在使用时比较安全。
2:如果使用Activity作为上下文环境,可能出现内存泄露的问题,所以在大多数的情况下,应该使用getApplicationContext()做为上下文环境,但是在操作对话框的使用,应该使用Activity。