Get请求方式
Get主要用于文件下载
将下载文件的代码封装在线程中,通过Handler去实现功能,代码如下:
public class DownloadThread extends Thread {
String u;
String path;
Handler handler;
public DownloadThread(Handler handler, String u, String path) {
this.u = u;
this.path = path;
this.handler = handler;
}
@Override
public void run() {
super.run();
InputStream is = null;
FileOutputStream fileOutputStream = null;
try {
URL url = new URL(u);
HttpURLConnection http = (HttpURLConnection) url.openConnection();
int contentLength = http.getContentLength();
Message message1 = Message.obtain();
message1.what=101;
message1.obj=contentLength;
handler.sendMessage(message1);
if (http.getResponseCode()==200) {
is = http.getInputStream();
fileOutputStream = new FileOutputStream(path);
byte[] bytes = new byte[1024];
int len = 0;
int count=0;
while ((len=is.read(bytes))!=-1) {
count+=len;
Thread.sleep(100);
fileOutputStream.write(bytes,0,len);
Message message2 = Message.obtain();
message2.what=100;
message2.obj=count;
handler.sendMessage(message2);
}
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
if (is!=null){
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fileOutputStream!=null){
try {
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
Post请求方式
Post主要用于上传
上传文件:post请求
-
设置请求头信息:
Content-Length:请求体的长度
Content-Type:multipart/form-data; boundary=7e324741816d4 -
请求体:
第一部分 要有换行
-----------------------------7e324741816d4
Content-Disposition: form-data; name=“file”; filename=“上传到服务器的名字”
Content-Type: media/mp4或者media/mp3或者image/mp3或者image/png
空行第二部分 需要上传的文件:边读边写
将上传文件的代码封装在线程中,通过Handler去实现功能,代码如下:
public class UploadThread extends Thread {
String u;
String path;
Handler handler;
String filname;
public UploadThread(Handler handler, String u, String path,String filname) {
this.handler = handler