android模拟post请求上传文件

这个是查看网上的资料及android sdk 开发范例书上的例子之后做出来的,基本上是粘过来的,只是添加了几句代码。下面是代码:

 

public static String uploadBitmap1(String urlString,byte[] imageBytes){

String endString = "/r/n";

String twoHyphen = "--";

String boundary = "*****";

try {

URL url = new URL(urlString);

final HttpURLConnection con = (HttpURLConnection)url.openConnection();

//允许input、Output,不使用Cache

con.setDoInput(true);

con.setDoOutput(true);

con.setUseCaches(false);

//设置传送的method=POST

con.setRequestMethod("POST");

//setRequestProperty

con.setRequestProperty("Connection", "Keep-Alive");

con.setRequestProperty("Charset", "UTF-8");

con.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary);

 

//从主机读取数据的超时时间(单位:毫秒) 

con.setReadTimeout(50000);

//设置连接主机的超时时间(单位:毫秒) 

con.setConnectTimeout(50000);

 

//System.out.println(con.getResponseCode());

//设置DataOutputStream

DataOutputStream dsDataOutputStream = new DataOutputStream(con.getOutputStream());

dsDataOutputStream.writeBytes(twoHyphen + boundary + endString);

dsDataOutputStream.writeBytes("Content-Disposition:form-data;" + "name=/"file1/";filename=/"" +

"11.jpg/"" + endString);

dsDataOutputStream.writeBytes(endString);

 

dsDataOutputStream.write(imageBytes,0,imageBytes.length);

dsDataOutputStream.writeBytes(endString);

dsDataOutputStream.writeBytes(twoHyphen + boundary + twoHyphen + endString);

 

dsDataOutputStream.close();

int cah = con.getResponseCode();

if(cah == 200){

InputStream isInputStream = con.getInputStream();

int ch;

StringBuffer buffer = new StringBuffer();

while((ch = isInputStream.read()) != -1){

buffer.append((char)ch);

}

return buffer.toString();

}else{

return "false";

}

} catch (Exception e) {

e.printStackTrace();

return "false";

}

}

 

 

传过来的参数中byte[] imageBytes是将图片或者是要上传的文件转换后得到的byte数组。其他的就不解释了,查看下面几个文章就知道了(网上找到的很不错的文章)。

http://zsnlovewl.javaeye.com/blog/636650

http://student.csdn.net/space.php?uid=46868&do=blog&id=25873

 

再写一个简单的Bitmap转换成Byte数组的代码:

 

ByteArrayOutputStream os = new ByteArrayOutputStream(); 

bm.compress(CompressFormat.JPEG, 70, os);

byte[] imgBytes = os.toByteArray(); 

bm是Bitmap对象。

 

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值