50,545
社区成员
发帖
与我相关
我的任务
分享
public String post(String fileParamName, String fileName, byte[] file,
Map<String, String> params) throws Exception {
HttpURLConnection huc = (HttpURLConnection) url.openConnection();
if (httpURL.startsWith("https")) {
HttpsURLConnection hucs = (HttpsURLConnection) huc;
TrustManager[] tm = { new MyX509TrustManager() };
SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
sslContext.init(null, tm, new java.security.SecureRandom());
SSLSocketFactory ssf = sslContext.getSocketFactory();
hucs.setSSLSocketFactory(ssf);
HttpsURLConnection.setDefaultSSLSocketFactory(ssf);
hucs.setHostnameVerifier(new TrustAnyHostnameVerifier());
}
huc.setRequestMethod("POST");
huc.setDoOutput(true);
huc.setDoInput(true);
huc.setConnectTimeout(connectTimeout);
huc.setReadTimeout(readTimeout);
String boundary = "-----------------------------114975832116442893661388290519";
huc.setRequestProperty("Content-Type", "multipart/form-data;boundary="
+ boundary);
boundary = "--" + boundary;
StringBuffer sb = new StringBuffer();
if (params != null) {
for (Iterator<String> it = params.keySet().iterator(); it.hasNext();) {
String k = it.next();
String v = params.get(k);
sb.append(boundary).append("\r\n");
sb.append("Content-Disposition: form-data; name=\"" + k
+ "\"\r\n\r\n");
sb.append(v).append("\r\n");
}
}
sb.append(boundary).append("\r\n");
sb.append("Content-Disposition: form-data; name=\"" + fileParamName
+ "\"; filename=\"" + fileName + "\"\r\n");
sb.append("Content-Type: " + getContentType(fileName) + " \r\n\r\n");
huc.connect();
OutputStream out = huc.getOutputStream();
out.write(sb.toString().getBytes("UTF-8"));
out.write(file);
out.flush();
out.close();
String err = checkError(huc);
if (err != null)
return err;
BufferedReader in = new BufferedReader(new InputStreamReader(
huc.getInputStream(), "ISO8859-1"));
StringBuffer resp = new StringBuffer();
String s = in.readLine();
while (s != null) {
resp.append(s);
s = in.readLine();
}
in.close();
return resp.toString();
}