add a post multipartFile for test

This commit is contained in:
fanfuxiaoran 2014-04-28 16:09:59 +08:00
parent 4dbbcd2f55
commit 75666ffde7
1 changed files with 425 additions and 390 deletions

View File

@ -1,390 +1,425 @@
package org.bench4q.share.communication; package org.bench4q.share.communication;
import java.io.BufferedReader; import java.io.BufferedReader;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.io.InputStreamReader; import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException; import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection; import java.net.HttpURLConnection;
import java.net.URL; import java.net.URL;
import java.net.URLEncoder; import java.net.URLEncoder;
import java.nio.charset.Charset; import java.nio.charset.Charset;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Map.Entry; import java.util.Map.Entry;
import org.apache.commons.httpclient.Header; import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.PostMethod; import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.multipart.FilePart; import org.apache.commons.httpclient.methods.multipart.FilePart;
import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity; import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity;
import org.apache.commons.httpclient.methods.multipart.Part; import org.apache.commons.httpclient.methods.multipart.Part;
import org.apache.commons.httpclient.methods.multipart.StringPart; import org.apache.commons.httpclient.methods.multipart.PartSource;
import org.springframework.stereotype.Component; import org.apache.commons.httpclient.methods.multipart.StringPart;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
@Component import org.springframework.web.multipart.commons.CommonsMultipartFile;
public class HttpRequester {
private String defaultContentEncoding; @Component
private HttpClient httpClient; public class HttpRequester {
private String defaultContentEncoding;
private HttpClient getHttpClient() { private HttpClient httpClient;
return httpClient;
} private HttpClient getHttpClient() {
return httpClient;
private void setHttpClient(HttpClient httpClient) { }
this.httpClient = httpClient;
} private void setHttpClient(HttpClient httpClient) {
this.httpClient = httpClient;
public HttpRequester() { }
this.setDefaultContentEncoding(Charset.defaultCharset().name());
this.setHttpClient(new HttpClient()); public HttpRequester() {
} this.setDefaultContentEncoding(Charset.defaultCharset().name());
this.setHttpClient(new HttpClient());
public String getDefaultContentEncoding() { }
return defaultContentEncoding;
} public String getDefaultContentEncoding() {
return defaultContentEncoding;
public void setDefaultContentEncoding(String defaultContentEncoding) { }
this.defaultContentEncoding = defaultContentEncoding;
} public void setDefaultContentEncoding(String defaultContentEncoding) {
this.defaultContentEncoding = defaultContentEncoding;
public HttpResponse sendPost(String urlString, Map<String, String> params, }
Map<String, String> properties) throws IOException {
return this.send(urlString, "POST", params, "", properties); public HttpResponse sendPost(String urlString, Map<String, String> params,
} Map<String, String> properties) throws IOException {
return this.send(urlString, "POST", params, "", properties);
public static boolean isInvalidResponse(HttpResponse httpResponse) { }
return httpResponse == null || httpResponse.getContent() == null;
} public static boolean isInvalidResponse(HttpResponse httpResponse) {
return httpResponse == null || httpResponse.getContent() == null;
public HttpResponse sendPostXml(String urlString, String contentString, }
Map<String, String> properties) throws IOException {
if (properties == null) { public HttpResponse sendPostXml(String urlString, String contentString,
properties = new HashMap<String, String>(); Map<String, String> properties) throws IOException {
} if (properties == null) {
properties.put("Content-Type", "application/xml"); properties = new HashMap<String, String>();
return this.send(urlString, "POST", null, contentString, properties); }
} properties.put("Content-Type", "application/xml");
return this.send(urlString, "POST", null, contentString, properties);
public HttpResponse sendGet(String urlString, Map<String, String> params, }
Map<String, String> properties) throws IOException {
public HttpResponse sendGet(String urlString, Map<String, String> params,
return this.send(urlString, "GET", params, "", properties); Map<String, String> properties) throws IOException {
}
return this.send(urlString, "GET", params, "", properties);
public HttpResponse sendPutXml(String urlString, String content, }
Map<String, String> properties) throws IOException {
if (properties == null) { public HttpResponse sendPutXml(String urlString, String content,
properties = new HashMap<String, String>(); Map<String, String> properties) throws IOException {
} if (properties == null) {
properties.put("Content-Type", "application/xml"); properties = new HashMap<String, String>();
return this.send(urlString, "PUT", null, content, properties); }
} properties.put("Content-Type", "application/xml");
return this.send(urlString, "PUT", null, content, properties);
public HttpResponse postFile(String url, String name, String filePath) { }
PostMethod postMethod = new PostMethod(url);
try { public HttpResponse postFile(String url, String name, String filePath) {
FilePart filePart = new FilePart(name, new File(filePath)); PostMethod postMethod = new PostMethod(url);
postMethod.setRequestEntity(new MultipartRequestEntity( try {
new FilePart[] { filePart }, postMethod.getParams())); FilePart filePart = new FilePart(name, new File(filePath));
return buildResponseWithMethod(postMethod); postMethod.setRequestEntity(new MultipartRequestEntity(
} catch (Exception e) { new FilePart[] { filePart }, postMethod.getParams()));
e.printStackTrace(); return buildResponseWithMethod(postMethod);
postMethod = null; } catch (Exception e) {
return null; e.printStackTrace();
} finally { postMethod = null;
postMethod.releaseConnection(); return null;
} } finally {
} postMethod.releaseConnection();
}
private HttpResponse buildResponseWithMethod(PostMethod postMethod) }
throws IOException {
HttpResponse httpResponse = new HttpResponse(); private HttpResponse buildResponseWithMethod(PostMethod postMethod)
int statusCode = this.getHttpClient().executeMethod(postMethod); throws IOException {
httpResponse.setCode(statusCode); HttpResponse httpResponse = new HttpResponse();
httpResponse.setContent(postMethod.getResponseBodyAsString()); int statusCode = this.getHttpClient().executeMethod(postMethod);
httpResponse.setContentType(postMethod httpResponse.setCode(statusCode);
.getResponseHeader("Content-Type").equals(null) ? postMethod httpResponse.setContent(postMethod.getResponseBodyAsString());
.getResponseHeader("Content-Type").getValue() : null); httpResponse.setContentType(postMethod
httpResponse.setContentEncoding(postMethod.getResponseCharSet()); .getResponseHeader("Content-Type").equals(null) ? postMethod
return httpResponse; .getResponseHeader("Content-Type").getValue() : null);
} httpResponse.setContentEncoding(postMethod.getResponseCharSet());
return httpResponse;
public HttpResponse postFiles(Map<String, String> headers, String url, }
String filePartName, List<File> files, String stringPartName,
List<String> strings) { public HttpResponse postFiles(Map<String, String> headers, String url,
if (!url.startsWith("http")) String filePartName, List<File> files, String stringPartName,
url = "http://" + url; List<String> strings){
PostMethod postMethod = new PostMethod(url); if (!url.startsWith("http"))
url = "http://" + url;
PostMethod postMethod = new PostMethod(url);
try {
if (headers != null) { try {
if (headers != null) {
for (Entry<String, String> entry : headers.entrySet()) {
Header header=new Header(entry.getKey(), entry.getValue()); for (Entry<String, String> entry : headers.entrySet()) {
postMethod.addRequestHeader(header); Header header = new Header(entry.getKey(), entry.getValue());
} postMethod.addRequestHeader(header);
}
} }
Part[] parts = new Part[files.size() + strings.size()]; Part[] parts = new Part[files.size() + strings.size()];
for (int i = 0; i < files.size(); i++) { for (int i = 0; i < files.size(); i++) {
parts[i] = new FilePart(filePartName, files.get(i)); parts[i] = new FilePart(filePartName, files.get(i));
} }
for (int i = 0; i < strings.size(); i++) { for (int i = 0; i < strings.size(); i++) {
parts[i + files.size()] = new StringPart(stringPartName, parts[i + files.size()] = new StringPart(stringPartName,
strings.get(i)); strings.get(i));
} }
postMethod.setRequestEntity(new MultipartRequestEntity(parts, postMethod.setRequestEntity(new MultipartRequestEntity(parts,
postMethod.getParams())); postMethod.getParams()));
return buildResponseWithMethod(postMethod); return buildResponseWithMethod(postMethod);
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
return null; return null;
} finally { } finally {
postMethod.releaseConnection(); postMethod.releaseConnection();
} }
}
} public HttpResponse postFilesMulti(Map<String, String> headers, String url,
String filePartName, CommonsMultipartFile[] paramFiles, String stringPartName,
private HttpResponse send(String urlString, String method, List<String> strings) {
Map<String, String> parameters, String Content, if (!url.startsWith("http"))
Map<String, String> propertys) throws IOException { url = "http://" + url;
HttpURLConnection urlConnection = null; PostMethod postMethod = new PostMethod(url);
if (method.equalsIgnoreCase("GET") && parameters != null) { try {
StringBuffer param = new StringBuffer(); if (headers != null) {
int i = 0;
for (String key : parameters.keySet()) { for (Entry<String, String> entry : headers.entrySet()) {
if (i == 0) Header header = new Header(entry.getKey(), entry.getValue());
param.append("?"); postMethod.addRequestHeader(header);
else }
param.append("&");
String encodedValue = URLEncoder.encode(parameters.get(key), }
"UTF-8"); Part[] parts = new Part[paramFiles.length + strings.size()];
param.append(key).append("=").append(encodedValue); for (int i = 0; i < paramFiles.length; i++) {
i++; parts[i] = new FilePart(filePartName, (PartSource) paramFiles[i]);
} }
urlString += param; for (int i = 0; i < strings.size(); i++) {
} parts[i + paramFiles.length] = new StringPart(stringPartName,
strings.get(i));
if (!urlString.startsWith("http://")) { }
urlString = "http://" + urlString; postMethod.setRequestEntity(new MultipartRequestEntity(parts,
} postMethod.getParams()));
URL url = new URL(urlString); return buildResponseWithMethod(postMethod);
urlConnection = (HttpURLConnection) url.openConnection(); } catch (Exception e) {
urlConnection.setRequestMethod(method); e.printStackTrace();
urlConnection.setDoOutput(true); return null;
urlConnection.setDoInput(true); } finally {
urlConnection.setUseCaches(false); postMethod.releaseConnection();
if (propertys != null) }
for (String key : propertys.keySet()) {
urlConnection.addRequestProperty(key, propertys.get(key)); }
}
private HttpResponse send(String urlString, String method,
if ((method.equalsIgnoreCase("POST") || method.equalsIgnoreCase("PUT")) Map<String, String> parameters, String Content,
&& parameters != null) { Map<String, String> propertys) throws IOException {
StringBuffer param = new StringBuffer(); HttpURLConnection urlConnection = null;
for (String key : parameters.keySet()) {
param.append("&"); if (method.equalsIgnoreCase("GET") && parameters != null) {
String encodedValueString = URLEncoder.encode( StringBuffer param = new StringBuffer();
parameters.get(key), "UTF-8"); int i = 0;
param.append(key).append("=").append(encodedValueString); for (String key : parameters.keySet()) {
} if (i == 0)
urlConnection.getOutputStream().write(param.toString().getBytes()); param.append("?");
urlConnection.getOutputStream().flush(); else
urlConnection.getOutputStream().close(); param.append("&");
} else if ((method.equalsIgnoreCase("POST") || method String encodedValue = URLEncoder.encode(parameters.get(key),
.equalsIgnoreCase("PUT")) && !Content.isEmpty()) { "UTF-8");
urlConnection.getOutputStream().write(Content.getBytes()); param.append(key).append("=").append(encodedValue);
urlConnection.getOutputStream().flush(); i++;
urlConnection.getOutputStream().close(); }
} urlString += param;
return this.makeContent(urlString, urlConnection); }
}
if (!urlString.startsWith("http://")) {
private HttpResponse makeContent(String urlString, urlString = "http://" + urlString;
HttpURLConnection urlConnection) { }
InputStream in; URL url = new URL(urlString);
try { urlConnection = (HttpURLConnection) url.openConnection();
in = urlConnection.getInputStream(); urlConnection.setRequestMethod(method);
return buildHttpResponse(urlConnection, urlConnection.setDoOutput(true);
readConnectionInputStream(in)); urlConnection.setDoInput(true);
} catch (IOException e) { urlConnection.setUseCaches(false);
in = urlConnection.getErrorStream(); if (propertys != null)
try { for (String key : propertys.keySet()) {
return buildHttpResponse(urlConnection, urlConnection.addRequestProperty(key, propertys.get(key));
readConnectionInputStream(in)); }
} catch (Exception e1) {
return getDefaultErrorResponse(); if ((method.equalsIgnoreCase("POST") || method.equalsIgnoreCase("PUT"))
} && parameters != null) {
} finally { StringBuffer param = new StringBuffer();
if (urlConnection != null) { for (String key : parameters.keySet()) {
urlConnection.disconnect(); param.append("&");
} String encodedValueString = URLEncoder.encode(
} parameters.get(key), "UTF-8");
param.append(key).append("=").append(encodedValueString);
} }
urlConnection.getOutputStream().write(param.toString().getBytes());
private HttpResponse buildHttpResponse(HttpURLConnection urlConnection, urlConnection.getOutputStream().flush();
StringBuffer temp) throws UnsupportedEncodingException, IOException { urlConnection.getOutputStream().close();
HttpResponse httpResponser = new HttpResponse(); } else if ((method.equalsIgnoreCase("POST") || method
httpResponser.setUrlString(urlConnection.getURL().getPath()); .equalsIgnoreCase("PUT")) && !Content.isEmpty()) {
httpResponser.setDefaultPort(urlConnection.getURL().getDefaultPort()); urlConnection.getOutputStream().write(Content.getBytes());
httpResponser.setPort(urlConnection.getURL().getPort()); urlConnection.getOutputStream().flush();
httpResponser.setProtocol(urlConnection.getURL().getProtocol()); urlConnection.getOutputStream().close();
String ecod = urlConnection.getContentEncoding(); }
if (ecod == null) return this.makeContent(urlString, urlConnection);
ecod = this.defaultContentEncoding; }
httpResponser.setContent(new String(temp.toString().getBytes(), ecod));
httpResponser.setContentEncoding(ecod); private HttpResponse makeContent(String urlString,
httpResponser.setCode(urlConnection.getResponseCode()); HttpURLConnection urlConnection) {
httpResponser.setMessage(urlConnection.getResponseMessage()); InputStream in;
httpResponser.setContentType(urlConnection.getContentType()); try {
httpResponser.setConnectTimeout(urlConnection.getConnectTimeout()); in = urlConnection.getInputStream();
httpResponser.setReadTimeout(urlConnection.getReadTimeout()); return buildHttpResponse(urlConnection,
return httpResponser; readConnectionInputStream(in));
} } catch (IOException e) {
e.printStackTrace();
private StringBuffer readConnectionInputStream(InputStream in) in = urlConnection.getErrorStream();
throws IOException { try {
StringBuffer ret = new StringBuffer(); return buildHttpResponse(urlConnection,
BufferedReader bufferedReader = new BufferedReader( readConnectionInputStream(in));
new InputStreamReader(in)); } catch (Exception e1) {
String line = bufferedReader.readLine(); return getDefaultErrorResponse();
while (line != null) { }
ret.append(line).append("\r\n"); } finally {
line = bufferedReader.readLine(); if (urlConnection != null) {
} urlConnection.disconnect();
bufferedReader.close(); }
return ret; }
}
}
private HttpResponse getDefaultErrorResponse() {
HttpResponse httpResponse = new HttpResponse(); private HttpResponse buildHttpResponse(HttpURLConnection urlConnection,
return httpResponse; StringBuffer temp) throws UnsupportedEncodingException, IOException {
} HttpResponse httpResponser = new HttpResponse();
httpResponser.setUrlString(urlConnection.getURL().getPath());
public static class HttpResponse { httpResponser.setDefaultPort(urlConnection.getURL().getDefaultPort());
httpResponser.setPort(urlConnection.getURL().getPort());
String urlString; httpResponser.setProtocol(urlConnection.getURL().getProtocol());
String ecod = urlConnection.getContentEncoding();
int defaultPort; if (ecod == null)
ecod = this.defaultContentEncoding;
int port; httpResponser.setContent(new String(temp.toString().getBytes(), ecod));
httpResponser.setContentEncoding(ecod);
String protocol; httpResponser.setCode(urlConnection.getResponseCode());
httpResponser.setMessage(urlConnection.getResponseMessage());
String contentEncoding; httpResponser.setContentType(urlConnection.getContentType());
httpResponser.setConnectTimeout(urlConnection.getConnectTimeout());
String content; httpResponser.setReadTimeout(urlConnection.getReadTimeout());
return httpResponser;
String contentType; }
int code; private StringBuffer readConnectionInputStream(InputStream in)
throws IOException {
String message; StringBuffer ret = new StringBuffer();
BufferedReader bufferedReader = new BufferedReader(
int connectTimeout; new InputStreamReader(in));
String line = bufferedReader.readLine();
int readTimeout; while (line != null) {
ret.append(line).append("\r\n");
public String getUrlString() { line = bufferedReader.readLine();
return urlString; }
} bufferedReader.close();
return ret;
public void setUrlString(String urlString) { }
this.urlString = urlString;
} private HttpResponse getDefaultErrorResponse() {
HttpResponse httpResponse = new HttpResponse();
public int getDefaultPort() { return httpResponse;
return defaultPort; }
}
public static class HttpResponse {
public void setDefaultPort(int defaultPort) {
this.defaultPort = defaultPort; String urlString;
}
int defaultPort;
public int getPort() {
return port; int port;
}
String protocol;
public void setPort(int port) {
this.port = port; String contentEncoding;
}
String content;
public String getProtocol() {
return protocol; String contentType;
}
int code;
public void setProtocol(String protocol) {
this.protocol = protocol; String message;
}
int connectTimeout;
public String getContentEncoding() {
return contentEncoding; int readTimeout;
}
public String getUrlString() {
public void setContentEncoding(String contentEncoding) { return urlString;
this.contentEncoding = contentEncoding; }
}
public void setUrlString(String urlString) {
public String getContent() { this.urlString = urlString;
return content; }
}
public int getDefaultPort() {
public void setContent(String content) { return defaultPort;
this.content = content; }
}
public void setDefaultPort(int defaultPort) {
public String getContentType() { this.defaultPort = defaultPort;
return contentType; }
}
public int getPort() {
public void setContentType(String contentType) { return port;
this.contentType = contentType; }
}
public void setPort(int port) {
public int getCode() { this.port = port;
return code; }
}
public String getProtocol() {
public void setCode(int code) { return protocol;
this.code = code; }
}
public void setProtocol(String protocol) {
public String getMessage() { this.protocol = protocol;
return message; }
}
public String getContentEncoding() {
public void setMessage(String message) { return contentEncoding;
this.message = message; }
}
public void setContentEncoding(String contentEncoding) {
public int getConnectTimeout() { this.contentEncoding = contentEncoding;
return connectTimeout; }
}
public String getContent() {
public void setConnectTimeout(int connectTimeout) { return content;
this.connectTimeout = connectTimeout; }
}
public void setContent(String content) {
public int getReadTimeout() { this.content = content;
return readTimeout; }
}
public String getContentType() {
public void setReadTimeout(int readTimeout) { return contentType;
this.readTimeout = readTimeout; }
}
public void setContentType(String contentType) {
public static String[] getStringArray(String content) { this.contentType = contentType;
content = content.substring(1, content.length() - 1); }
return content.split(",");
} public int getCode() {
return code;
} }
}
public void setCode(int code) {
this.code = code;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public int getConnectTimeout() {
return connectTimeout;
}
public void setConnectTimeout(int connectTimeout) {
this.connectTimeout = connectTimeout;
}
public int getReadTimeout() {
return readTimeout;
}
public void setReadTimeout(int readTimeout) {
this.readTimeout = readTimeout;
}
public static String[] getStringArray(String content) {
content = content.substring(1, content.length() - 1);
return content.split(",");
}
}
}