package net.wujingchao.android.utility
import android.content.Context;
import android.os.Environment;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.util.UUID;
import com.mixiaofan.App;
public class DownloadUtil {
private static final int TIME_OUT = 30*1000; //超時(shí)時(shí)間
private static final String CHARSET = "utf-8" ; //設(shè)置編碼
private DownloadUtil() {
throw new UnsupportedOperationException( "DownloadUtil cannot be instantiated" );
}
/**
* @param file 上傳文件
* @param RequestURL 上傳文件URL
* @return 服務(wù)器返回的信息,如果出錯(cuò)則返回為null
*/
public static String uploadFile(File file,String RequestURL) {
String BOUNDARY = UUID.randomUUID().toString(); //邊界標(biāo)識(shí) 隨機(jī)生成 String PREFIX = "--" , LINE_END = "\r\n";
String PREFIX = "--" , LINE_END = "\r\n" ;
String CONTENT_TYPE = "multipart/form-data" ; //內(nèi)容類型
try {
URL url = new URL(RequestURL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(TIME_OUT);
conn.setConnectTimeout(TIME_OUT);
conn.setDoInput( true ); //允許輸入流
conn.setDoOutput( true ); //允許輸出流
conn.setUseCaches( false ); //不允許使用緩存
conn.setRequestMethod( "POST" ); //請(qǐng)求方式
conn.setRequestProperty( "Charset" , CHARSET);
conn.setRequestProperty( "Cookie" , "PHPSESSID=" + App.getSessionId());
//設(shè)置編碼
conn.setRequestProperty( "connection" , "keep-alive" );
conn.setRequestProperty( "Content-Type" , CONTENT_TYPE + ";boundary=" + BOUNDARY);
if (file!= null ) {
/** * 當(dāng)文件不為空,把文件包裝并且上傳 */
OutputStream outputSteam=conn.getOutputStream();
DataOutputStream dos = new DataOutputStream(outputSteam);
StringBuffer sb = new StringBuffer();
sb.append(PREFIX);
sb.append(BOUNDARY); sb.append(LINE_END);
/**
* 這里重點(diǎn)注意:
* name里面的值為服務(wù)器端需要key 只有這個(gè)key 才可以得到對(duì)應(yīng)的文件
* filename是文件的名字,包含后綴名的 比如:abc.png
*/
sb.append( "Content-Disposition: form-data; name=\"img\"; filename=\"" +file.getName()+ "\"" +LINE_END);
sb.append( "Content-Type: application/octet-stream; charset=" +CHARSET+LINE_END);
sb.append(LINE_END);
dos.write(sb.toString().getBytes());
InputStream is = new FileInputStream(file);
byte[] bytes = new byte[1024];
int len;
while ((len=is.read(bytes))!=-1)
{
dos.write(bytes, 0, len);
}
is.close();
dos.write(LINE_END.getBytes());
byte[] end_data = (PREFIX+BOUNDARY+PREFIX+LINE_END).getBytes();
dos.write(end_data);
dos.flush();
/**
* 獲取響應(yīng)碼 200=成功
* 當(dāng)響應(yīng)成功,獲取響應(yīng)的流
*/
ByteArrayOutputStream bos = new ByteArrayOutputStream();
InputStream resultStream = conn.getInputStream();
len = -1;
byte [] buffer = new byte[1024*8];
while ((len = resultStream.read(buffer)) != -1) {
bos.write(buffer,0,len);
}
resultStream.close();
bos.flush();
bos.close();
String info = new String(bos.toByteArray());
int res = conn.getResponseCode();
if (res==200){
return info;
} else {
return null ;
}
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null ;
}
public static byte[] download(String urlStr) {
HttpURLConnection conn = null ;
InputStream is = null ;
byte[] result = null ;
ByteArrayOutputStream bos = null ;
try {
URL url = new URL(urlStr);
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod( "GET" );
conn.setConnectTimeout(TIME_OUT);
conn.setReadTimeout(TIME_OUT);
conn.setDoInput( true );
conn.setUseCaches( false ); //不使用緩存
if (conn.getResponseCode() == 200) {
is = conn.getInputStream();
byte [] buffer = new byte[1024*8];
int len;
bos = new ByteArrayOutputStream();
while ((len = is.read(buffer)) != -1) {
bos.write(buffer,0,len);
}
bos.flush();
result = bos.toByteArray();
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (bos != null ){
bos.close();
}
if (is != null ) {
is.close();
}
if (conn != null )conn.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
return result;
}
/**
* 獲取緩存文件
*/
public static File getDiskCacheFile(Context context,String filename,boolean isExternal) {
if (isExternal && (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED))) {
return new File(context.getExternalCacheDir(),filename);
} else {
return new File(context.getCacheDir(),filename);
}
}
/**
* 獲取緩存文件目錄
*/
public static File getDiskCacheDirectory(Context context) {
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
return context.getExternalCacheDir();
} else {
return context.getCacheDir();
}
}
}
|