67,513
社区成员
发帖
与我相关
我的任务
分享
public static String sendRequest(String url, Map<String, String> params,
Map<String, File> files) throws Exception {
HttpURLConnection conn = (HttpURLConnection) new URL(url)
.openConnection();
String BOUNDARY = java.util.UUID.randomUUID().toString();
String PREFIX = "--", LINEND = "\r\n";
String MULTIPART_FROM_DATA = "application/octet-stream";
String CHARSET = "UTF-8";
conn.setConnectTimeout(5 * 1000);
conn.setRequestMethod("POST");
conn.setRequestProperty("Charset", "UTF-8");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
conn.setRequestProperty("Content-Type", MULTIPART_FROM_DATA
+ ";boundary=" + BOUNDARY);
// 首先组拼文本类型的参数
StringBuilder sb = new StringBuilder();
System.out.println(url);
DataOutputStream outStream = new DataOutputStream(conn.getOutputStream());
// outStream.write(sb.toString().getBytes());
// 发送文件数据
if (files != null)
for (Map.Entry<String, File> file : files.entrySet()) {
StringBuilder sb1 = new StringBuilder();
sb1.append(PREFIX);
sb1.append(BOUNDARY);
sb1.append(LINEND);
sb1.append("Content-Disposition: form-data; name=\"file\"; filename=\""
+ file.getKey() + "\"" + LINEND);
sb1.append("Content-Type: application/octet-stream; charset="
+ CHARSET + LINEND);
sb1.append(LINEND);
outStream.write(sb1.toString().getBytes());
InputStream is = new FileInputStream(file.getValue());
byte[] buffer = new byte[1024];
int len = 0;
while ((len = is.read(buffer)) != -1) {
outStream.write(buffer, 0, len);
}
is.close();
outStream.write(LINEND.getBytes());
}
byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINEND).getBytes();
outStream.write(end_data);
outStream.flush();
int res = conn.getResponseCode();
System.out.println("response Code==="+res);
if (res == 200) {
InputStream in = conn.getInputStream();
int ch;
StringBuilder sb2 = new StringBuilder();
BufferedReader bw=new BufferedReader(new InputStreamReader(in,CHARSET));
String line="";
while((line=bw.readLine())!=null){
sb2.append(line);
}
System.out.println(sb2);
in.close();
return sb2.toString();
}
outStream.close();
conn.disconnect();
return null;
}
InputStream inputStream=request.getInputStream();
BufferedReader buf=new BufferedReader(new InputStreamReader(inputStream,"utf-8"));
String line="";
while((line=buf.readLine())!=null)
System.out.println(line);
StringBuilder sb = new StringBuilder();
for (Map.Entry<String, String> entry : params.entrySet())
{
sb.append(PREFIX);
sb.append(BOUNDARY);
sb.append(LINEND);
sb.append("Content-Disposition: form-data; name=\"" + entry.getKey() + "\"" + LINEND);
sb.append("Content-Type: text/plain; charset=" + CHARSET + LINEND);
sb.append("Content-Transfer-Encoding: 8bit" + LINEND);
sb.append(LINEND);
sb.append(entry.getValue());
sb.append(LINEND);
}
DataOutputStream outStream = new DataOutputStream(conn.getOutputStream());
outStream.write(sb.toString().getBytes());