import android.os.Environment;
import android.os.Message;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
/**
* HttpURLConnection工具类
*/
public class HttpURLConnectionUtil {
//POST请求 传递参数 ,下载文件
/**
* 下载文件保存到手机本地
* @param path http路径
* @param param json字符串 传递的参数
* @param filename 文件的名称
* @return
* @throws Exception
*/
public static File getFileFromServer(String path, String param, String filename) throws Exception{
Logs.i(path+param);
// 如果相等的话表示当前的sdcard挂载在手机上并且是可用的
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
OutputStream out = null; //写
// InputStream in = null; //读
Logs.i("开始下载");
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
//设置头部信息
// conn.setRequestProperty("headerdata", "ceshiyongde");
//一定要设置 Content-Type 要不然服务端接收不到参数
conn.setRequestProperty("Content-Type", "application/Json; charset=UTF-8");
//指示应用程序要将数据写入URL连接,其值默认为false(是否传参)
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setConnectTimeout(5000);
conn.setRequestProperty("Accept-Encoding", "identity");
conn.setRequestProperty("Connection", "Keep-Alive");
//传入参数
out = conn.getOutputStream();
out.write(param.getBytes());
// 正文,正文内容其实跟get的URL中 '? '后的参数字符串一致
//String content = "account=" + URLEncoder.encode("hahahaha", "UTF-8");
//content +="&pswd="+URLEncoder.encode("heiheihei", "UTF-8");;
// out.writeBytes(content);
out.flush(); //清空缓冲区,发送数据
out.close();
// conn.connect();
String fileType = conn.getContentType();//要下载文件的类型
Logs.i("conn.getContentType() "+conn.getContentType());
// 获取到文件的大小
// pd.setMax(conn.getContentLength());
Logs.i("file 的总大小 "+ conn.getContentLength());
final int totalBytes = conn.getContentLength();
InputStream is = conn.getInputStream();
File sd1 = Environment.getExternalStorageDirectory();
String path1 = sd1.getPath() + "/farmland/"+CacheUtil.Userid;
path1 = "/storage/emulated/0/farmland/1";
String fileName = filename+".jpg";
File myfile1 = new File(path1);
if (!myfile1.exists()) {
myfile1.mkdirs();//创建想要保存到的文件夹 mkdirs()能同时创建多级文件夹,mkdir()只能创建一级文件夹
Logs.i("创建文件夹成功 "+myfile1.getAbsolutePath());
}
File file = new File(myfile1, fileName);
FileOutputStream fos = new FileOutputStream(file);
BufferedInputStream bis = new BufferedInputStream(is);
Logs.i("创建文件成功 "+file.getAbsolutePath());
byte[] buffer = new byte[1024];
int len;
int total = 0;
while ((len = bis.read(buffer)) != -1) {
fos.write(buffer, 0, len);
total += len;
// 获取当前下载量
}
Logs.i(file.getPath()+"下载完成");
// imagePath = "/storage/emulated/0/farmland/1/"+filename+".jpg";
fos.close();
bis.close();
is.close();
return file;
} else {
return null;
}
}
}
在接收端,这样获取参数:
String name = request.getParameter("account");
String pswd = request.getParameter("pswd");