下载和上传都必须在清单文件里注册SD卡权限
下载
InputStream it=null;
FileOutputStream fos=null;
try {
URL url = new URL(name);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setConnectTimeout(5000);
urlConnection.setReadTimeout(5000);
urlConnection.connect();
if(urlConnection.getResponseCode()==200){
it= urlConnection.getInputStream();
fos=new FileOutputStream(pase);
byte[] bytes=new byte[1024];
while((len =it.read(bytes))!=-1){
fos.write(bytes,0,len);
}
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
}finally {
if(it!=null){
try {
it.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(fos!=null){
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
上传文件
File file = new File(pase);
FileInputStream fis=null;
OutputStream ot=null;
int count =0;
try {
//请求头(特加)
StringBuilder sb=new StringBuilder();
sb.append("-----------------------------7e324741816d4"+"\r\n");
sb.append(“Content-Disposition: form-data; name=“file”; filename=“aad.mp4"”+”\r\n");
sb.append(“Content-Type: media/mp4” + “\r\n”);
sb.append("\r\n");
byte[] bytes = sb.toString().getBytes(“UTF-8”);
URL url = new URL(name);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setConnectTimeout(5000);
urlConnection.setReadTimeout(5000);
urlConnection.setRequestProperty(“Content-Length”,bytes.length+file.length()+"");
urlConnection.setRequestProperty(“Content-Type”,“multipart/form-data; boundary=7e324741816d4”);
urlConnection.setRequestMethod(“POST”);
urlConnection.setDoOutput(true);
ot=urlConnection.getOutputStream();
fis=new FileInputStream(pase);
int len =0;
byte[] bytes1=new byte[1024];
ot.write(bytes);
urlConnection.connect();
while((len =fis.read(bytes1))!=-1){
handler.sendMessage(message);
ot.write(bytes1,0,len);
}
if(urlConnection.getResponseCode()==200){
System.out.println("上传成功");
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
if(fis!=null){
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(ot!=null){
try {
ot.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}