HttpClient sending a GET request
-
Create a Client Object
HttpClient client = new Defaulthttpclient ();
-
Create a GET Request object
HttpGet hg = new HttpGet (path);
-
Send GET request, establish connection, return response header Object
HttpResponse hr = Hc.execute (Hg);
-
Gets the status line object, gets the status code, and if 200 indicates the request was successful
if(hr.getStatusLine().getStatusCode() == 200){ //拿到服务器返回的输入流 InputStream is = hr.getEntity().getContent(); String text = Utils.getTextFromStream(is);}
Send a POST request
//创建一个客户端对象 HttpClient client = new DefaultHttpClient(); //创建一个post请求对象 HttpPost hp = new HttpPost(path);
-
Put the data you want to submit to the server in the Post object
//要提交的数据以键值对的形式存在BasicNameValuePair对象中List<NameValuePair> parameters = new ArrayList<NameValuePair>();BasicNameValuePair bnvp = new BasicNameValuePair("name", name);BasicNameValuePair bnvp2 = new BasicNameValuePair("pass", pass);parameters.add(bnvp);parameters.add(bnvp2);//创建实体对象,指定进行URL编码的码表UrlEncodedFormEntity entity = new UrlEncodedFormEntity(parameters, "utf-8");//为post请求设置实体hp.setEntity(entity);
Asynchronous HttpClient framework sends a GET request
//创建异步的httpclient对象 AsyncHttpClient ahc = new AsyncHttpClient(); //发送get请求 ahc.get(path, new MyHandler());
-
Note the call timing of the Asynchttpresponsehandler two methods
class MyHandler extends AsyncHttpResponseHandler{ //http请求成功,返回码为200,系统回调此方法 @Override public void onSuccess(int statusCode, Header[] headers, //responseBody的内容就是服务器返回的数据 byte[] responseBody) { Toast.makeText(MainActivity.this, new String(responseBody), 0).show(); } //http请求失败,返回码不为200,系统回调此方法 @Override public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) { Toast.makeText(MainActivity.this, "返回码不为200", 0).show(); }}
Send a POST request
-
Encapsulate the data to be carried using the Requestparams object
//创建异步httpclient对象AsyncHttpClient ahc = new AsyncHttpClient();//创建RequestParams封装要携带的数据RequestParams rp = new RequestParams();rp.add("name", name);rp.add("pass", pass);//发送post请求ahc.post(path, rp, new MyHandler());
Multi-Threaded Download
Principle: The server CPU is allocated the same time slice for each thread, the server bandwidth is allocated evenly to each thread, so the more threads the client opens, the more server resources can be preempted.
Determine how much data each thread downloads
-
Send HTTP request to
String path = "http://192.168.1.102:8080/editplus.exe"; URL url = new URL(path);HttpURLConnection conn = (HttpURLConnection) url.openConnection();conn.setReadTimeout(5000);conn.setConnectTimeout(5000);conn.setRequestMethod("GET");
-
Get the total length of the file, and then create a temporary file of the same length
if(conn.getResponseCode() == 200){ //获得服务器流中数据的长度 int length = conn.getContentLength(); //创建一个临时文件存储下载的数据 RandomAccessFile raf = new RandomAccessFile(getFileName(path), "rwd"); //设置临时文件的大小 raf.setLength(length); raf.close();
-
Determine how much data the thread downloads
//计算每个线程下载多少数据 int blockSize = length / THREAD_COUNT;
Calculate the start and end locations of each thread's download data
for(int id = 1; id <= 3; id++){ //计算每个线程下载数据的开始位置和结束位置 int startIndex = (id - 1) * blockSize; int endIndex = id * blockSize - 1; if(id == THREAD_COUNT){ endIndex = length; } //开启线程,按照计算出来的开始结束位置开始下载数据 new DownLoadThread(startIndex, endIndex, id).start(); }
Send request to, request data from start to end position
String path = "http://192.168.1.102:8080/editplus.exe"; URL url = new URL(path); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setReadTimeout(5000); conn.setConnectTimeout(5000); conn.setRequestMethod("GET"); //向服务器请求部分数据 conn.setRequestProperty("Range", "bytes=" + startIndex + "-" + endIndex); conn.connect();
-
Download the requested data and store it in a temporary file
if(conn.getResponseCode() == 206){ InputStream is = conn.getInputStream(); RandomAccessFile raf = new RandomAccessFile(getFileName(path), "rwd"); //指定从哪个位置开始存放数据 raf.seek(startIndex); byte[] b = new byte[1024]; int len; while((len = is.read(b)) != -1){ raf.write(b, 0, len); } raf.close();}
Multi-threaded Download with breakpoint continuation
-
Define an int variable to record the total length of data downloaded by each thread, and then add the thread's download start location, and the result is that the next time the thread starts, the result is stored in the cached file
//用来记录当前线程总的下载长度int total = 0;while((len = is.read(b)) != -1){ raf.write(b, 0, len); total += len; //每次下载都把新的下载位置写入缓存文本文件 RandomAccessFile raf2 = new RandomAccessFile(threadId + ".txt", "rwd"); raf2.write((startIndex + total + "").getBytes()); raf2.close();}
-
The next time the download begins, the value in the cache file is read first, and the resulting value is the beginning of the line assigns
FileInputStream fis = new FileInputStream(file);BufferedReader br = new BufferedReader(new InputStreamReader(fis));String text = br.readLine();int newStartIndex = Integer.parseInt(text);//把读到的值作为新的开始位置startIndex = newStartIndex;fis.close();
-
After all three threads have been downloaded, delete the cache file
RUNNING_THREAD--;if(RUNNING_THREAD == 0){ for(int i = 0; i <= 3; i++){ File f = new File(i + ".txt"); f.delete(); }}
Mobile version of the breakpoint continued multi-threaded downloader
- Just paste the code directly here to use, remember when accessing the file path to change to the Android directory, add access to the network and external storage path
Show download progress with progress bar
-
Set the maximum value of the progress bar when you get the total length of the download file
//设置进度条的最大值pb.setMax(length);
-
The progress bar needs to show the overall download progress of three threads, so three threads each time they download, the length of the new download will be added to the progress bar
-
Defines an int global variable that records the total download length of three threads
int progress;
-
Refresh Progress bar
while((len = is.read(b)) != -1){ raf.write(b, 0, len); //把当前线程本次下载的长度加到进度条里 progress += len; pb.setProgress(progress);
-
Each time the breakpoint is downloaded, the download starts from the new starting position, and the progress bar is also displayed at the beginning of the new location, and the progress bar progress is also processed when the cache file is read to get a fresh download start location.
FileInputStream fis = new FileInputStream(file);BufferedReader br = new BufferedReader(new InputStreamReader(fis));String text = br.readLine();int newStartIndex = Integer.parseInt(text);//新开始位置减去原本的开始位置,得到已经下载的数据长度int alreadyDownload = newStartIndex - startIndex;//把已经下载的长度设置入进度条progress += alreadyDownload;
Add a text box to show percent progress
tv.setText(progress * 100 / pb.getMax() + "%");
Use of Httputils
The httputils itself supports multi-threaded breakpoint continuation, which is very convenient to use.
-
Create httputils object
httputils http = new Httputils ();
-
Download file
http.download (URL,//download request URL target,//Download Data save path and file name true,//whether to turn on breakpoint continuation true, If the server response header contains a file name, then automatically rename new requestcallback<file> () {//listen for download status//Download successful This method call @Override public V OID onsuccess (responseinfo<file> arg0) {tv.settext ("Download succeeded" + Arg0.result.getPath ()); }//Download failed This method call, such as the file has been downloaded, no network permissions, no access to the file, the method passed in a string parameter to tell the reason for failure @Override public void OnFailure (HttpException arg0, string ARG1) {tv.settext ("Download failed" + arg1); }//During the download process, a constant call to refresh the progress bar @Override public void onloading (long, Long, Boolean isuploading) {s Uper.onloading (total, Current, isuploading); Set the overall length of the progress bar Pb.setmax ((int) total); Sets the current progress of the progress bar (Pb.setprogress (int.)); Tv_progress.settext (Current * 100/total + "%");
}});
Network programming based on Android application development (II.)