62,634
社区成员




String urlPath = "http://www.xxxxx.com";
URL url = new URL(urlPath);// 得到网址
String BOUNDARY = "---------7d4a6d158c9";// 设置分隔线
byte[] end_data = ("\r\n--" + BOUNDARY + "--\r\n").getBytes();// 定义最后数据分隔线
HttpURLConnection conn = (HttpURLConnection) url.openConnection();//获得连接
// 参数设置
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setRequestMethod("POST");
OutputStream outputStream = conn.getOutputStream();//获得输出流
StringBuilder sb = new StringBuilder();
sb.append("--");
sb.append(BOUNDARY);
sb.append("\r\n");
sb.append("Content-Disposition: form-data;name=\"file1\";filename=\""
+ file.getName() + "\"\r\n");
sb.append("Content-Type:application/octet-stream\r\n\r\n");
sb.append(end_data);
byte[] data = sb.toString().getBytes();
outputStream.write(data);
// 开始上传
int outSize;
byte[] outBuff = new byte[1024];
while ((outSize = fileInputStream.read(outBuff, 0, 1024)) > 0) {
outputStream.write(outBuff, 0, outSize);// 开始上传
}
outputStream.flush();
outputStream.close();
fileInputStream.close();
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(urlPath);
MultipartEntity mpEntity = new MultipartEntity();
ContentBody cbFile = new FileBody(file);
mpEntity.addPart("file", cbFile);
Map<String, String> map = new HashMap<String, String>();
map.put("uuid", im);
map.put("token", token);
for (Map.Entry<String, String> entry : map.entrySet()) {
mpEntity.addPart(entry.getKey(), new StringBody(entry.getValue()));
}
post.setEntity(mpEntity);
HttpResponse response = client.execute(post);
String content = EntityUtils.toString(response.getEntity());
System.out.println(content);
client.getConnectionManager().shutdown();