使用HttpURLConnection上传文件

面试:你懂什么是分布式系统吗?Redis分布式锁都不会?>>>   hot3.png

void test(){

String uploadUrl = "http://localhost:8080/upload/UploadServlet";
String end = "\r\n";
String twoHyphens = "--";
String boundary = "******";
try
{
URL url = new URL(uploadUrl);
HttpURLConnection httpURLConnection = (HttpURLConnection) url
.openConnection();

//输入输出流
httpURLConnection.setDoInput(true);
httpURLConnection.setDoOutput(true);
httpURLConnection.setUseCaches(false);

//get,post必须大写
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setRequestProperty("Connection", "Keep-Alive");
httpURLConnection.setRequestProperty("Charset", "UTF-8");

// 必须在Content-Type请求头中指定分界符中的任意字符串
httpURLConnection.setRequestProperty("Content-Type",
"multipart/form-data;boundary=" + boundary);
//获取输出流对象,预备上传文件
DataOutputStream dos = new DataOutputStream(httpURLConnection
.getOutputStream());

//设置分界符,加end表示单独一行
dos.writeBytes(twoHyphens + boundary + end);

//设置与上传文件相关的信息
dos
.writeBytes("Content-Disposition: form-data; name=\"file\"; filename=\""
+ filename.substring(filename.lastIndexOf("/") + 1)
+ "\"" + end);

//在上传文件信息与文件的内容之间必须有一个空行
dos.writeBytes(end);

FileInputStream fis = new FileInputStream(filename);
byte[] buffer = new byte[8192]; // 8k
int count = 0;
while ((count = fis.read(buffer)) != -1)
{
dos.write(buffer, 0, count);

}
fis.close();

dos.writeBytes(end);
dos.writeBytes(twoHyphens + boundary + twoHyphens + end);
dos.flush();

InputStream is = httpURLConnection.getInputStream();
InputStreamReader isr = new InputStreamReader(is, "utf-8");
BufferedReader br = new BufferedReader(isr);
String result = br.readLine();

Toast.makeText(this, result, Toast.LENGTH_LONG).show();
dos.close();
is.close();


}
catch (Exception e)
{
setTitle(e.getMessage());
}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值