使用java的HttpURLconnnection模拟form上传 以及apache httpClient 直接上传文件

1、使用java的HttpURLconnnection上传
List<String> list = new ArrayList<String>(); // 上传多个文件使用
try {

// 定义数据分隔线
String BOUNDARY = "---------7d4a6d158c9"; 
byte[] end_data = ("\r\n--" + BOUNDARY + "--\r\n").getBytes();// 定义最后数据分隔线


URL url = new URL("http://localhost:8080/service/latent.latentinfo!addLatentBranch.action");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
// 发送POST请求必须设置如下两行
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("Charsert", "UTF-8");
conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);


OutputStream out = new DataOutputStream(conn.getOutputStream());

// int leng = list.size(); 上传多个文件时使用
// for (int i = 0; i < leng; i++) {
// String fname = list.get(i);
// 上传文件
File file = new File("G:/素材文档/19.jpg");
StringBuilder sb = new StringBuilder();
sb.append("--");
sb.append(BOUNDARY);
sb.append("\r\n");
sb.append("Content-Disposition: form-data;name=\"photo\";filename=\"" + file.getName() + "\"\r\n");
sb.append("Content-Type:application/octet-stream\r\n\r\n");


byte[] data = sb.toString().getBytes();
out.write(data);
DataInputStream in = new DataInputStream(new FileInputStream(
file));
int bytes = 0;
byte[] bufferOut = new byte[1024];
while ((bytes = in.read(bufferOut)) != -1) {
out.write(bufferOut, 0, bytes);
}
out.write("\r\n".getBytes()); // 多个文件时,二个文件之间加入这个
in.close();




//}
// json参数 
sb = new StringBuilder();
sb.append("--");
sb.append(BOUNDARY);
sb.append("\r\n");
sb.append("Content-Disposition: form-data;name=\"params\"\r\n\r\n");每个请求头后面是两个回车换行
out.write(sb.toString().getBytes());
out.write("{'user_name':'apple','channel_name':'测试渠道','channel_address':'(123.4,30.6)'}".getBytes());
out.write("\r\n".getBytes());
out.write(end_data);
out.flush();
out.close();


// 定义BufferedReader输入流来读取URL的响应
BufferedReader reader = new BufferedReader(new InputStreamReader(
conn.getInputStream()));
String line = null;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}


}
catch (Exception e) {
System.out.println("发送POST请求出现异常!" + e);
e.printStackTrace();
}
}


2.使用apache-httpclient上传
 
       // 图片地址
       String photo = "G:/素材文档/19.jpg";

// 定义请求url
       String uri = "http://localhost:8080/service/latent.latentinfo!addLatentBranch.action";
       
       // 实例化http客户端
       HttpClient httpClient = new DefaultHttpClient();
       // 实例化post提交方式
       HttpPost post = new HttpPost(uri);
      
       // 实例化参数对象
       MultipartEntity params = new MultipartEntity();
       
       // 添加json参数
       params.addPart("params", new StringBody("{'user_name':'apple','channel_name':'测试渠道','channel_address':'(123.4,30.6)'}",Charset.forName("UTF-8")));
       
       // 设置上传文件
       File file = new File("G:/素材文档/19.jpg");
       FileBody fileBody = new FileBody(file);
       params.addPart("photo", fileBody);
       params.addPart("photoName", new StringBody(file.getName()));
       
       // 将参数加入post请求体中
       post.setEntity(params);


       // 执行post请求并得到返回对象
       HttpResponse resp = httpClient.execute(post);
       
       // 解析返回对象
       HttpEntity entity = resp.getEntity();
       InputStream is = entity.getContent();
       BufferedReader reader = new BufferedReader(new InputStreamReader(is));
              StringBuffer buffer = new StringBuffer();
              String temp ;


            while ((temp = reader.readLine()) != null) {


                    buffer.append(temp);
            }
       
            System.out.println(buffer);
     
}
catch (Exception ex) {

ex.printStackTrace();
}















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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值