下面列出了怎么用org.apache.commons.httpclient.params.HttpMethodParams的API类实例代码及写法,或者点击链接到github查看源代码。
@Test(groups = "wso2.esb", description = "Sending HTTP1.0 message")
public void sendingHTTP10Message() throws Exception {
PostMethod post = new PostMethod(getProxyServiceURLHttp("StockQuoteProxyTestHTTPVersion"));
RequestEntity entity = new StringRequestEntity(getPayload(), "text/xml", "UTF-8");
post.setRequestEntity(entity);
post.setRequestHeader("SOAPAction", "urn:getQuote");
HttpMethodParams params = new HttpMethodParams();
params.setVersion(HttpVersion.HTTP_1_0);
post.setParams(params);
HttpClient httpClient = new HttpClient();
String httpVersion = "";
try {
httpClient.executeMethod(post);
post.getResponseBodyAsString();
httpVersion = post.getStatusLine().getHttpVersion();
} finally {
post.releaseConnection();
}
Assert.assertEquals(httpVersion, HttpVersion.HTTP_1_0.toString(), "Http version mismatched");
}
@Test(groups = "wso2.esb", description = "Sending HTTP1.1 message")
public void sendingHTTP11Message() throws Exception {
PostMethod post = new PostMethod(getProxyServiceURLHttp("StockQuoteProxyTestHTTPVersion"));
RequestEntity entity = new StringRequestEntity(getPayload(), "text/xml", "UTF-8");
post.setRequestEntity(entity);
post.setRequestHeader("SOAPAction", "urn:getQuote");
HttpMethodParams params = new HttpMethodParams();
params.setVersion(HttpVersion.HTTP_1_1);
post.setParams(params);
HttpClient httpClient = new HttpClient();
String httpVersion = "";
try {
httpClient.executeMethod(post);
post.getResponseBodyAsString();
httpVersion = post.getStatusLine().getHttpVersion();
} finally {
post.releaseConnection();
}
Assert.assertEquals(httpVersion, HttpVersion.HTTP_1_1.toString(), "Http version mismatched");
}
public static String sendPost(String urlParam) throws HttpException, IOException {
// 创建httpClient实例对象
HttpClient httpClient = new HttpClient();
// 设置httpClient连接主机服务器超时时间:15000毫秒
httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(15000);
// 创建post请求方法实例对象
PostMethod postMethod = new PostMethod(urlParam);
// 设置post请求超时时间
postMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 60000);
postMethod.addRequestHeader("Content-Type", "application/json");
httpClient.executeMethod(postMethod);
String result = postMethod.getResponseBodyAsString();
postMethod.releaseConnection();
return result;
}
public static String sendGet(String urlParam) throws HttpException, IOException {
// 创建httpClient实例对象
HttpClient httpClient = new HttpClient();
// 设置httpClient连接主机服务器超时时间:15000毫秒
httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(15000);
// 创建GET请求方法实例对象
GetMethod getMethod = new GetMethod(urlParam);
// 设置post请求超时时间
getMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 60000);
getMethod.addRequestHeader("Content-Type", "application/json");
httpClient.executeMethod(getMethod);
String result = getMethod.getResponseBodyAsString();
getMethod.releaseConnection();
return result;
}
public static void callAPI(String url, String user, String uToken) throws HttpException, IOException {
if(url.indexOf("?") < 0) {
url += "?uName=" +user+ "&uToken=" + uToken;
}
else {
url += "&uName=" +user+ "&uToken=" + uToken;
}
PostMethod postMethod = new PostMethod(url);
postMethod.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "utf-8");
// 最后生成一个HttpClient对象,并发出postMethod请求
HttpClient httpClient = new HttpClient();
int statusCode = httpClient.executeMethod(postMethod);
if(statusCode == 200) {
System.out.print("返回结果: ");
String soapResponseData = postMethod.getResponseBodyAsString();
System.out.println(soapResponseData);
}
else {
System.out.println("调用失败!错误码:" + statusCode);
}
}
public static ServerStatus configureHttpMethod(HttpMethod method, Cloud cloud) throws JSONException {
method.addRequestHeader(new Header("Accept", "application/json"));
method.addRequestHeader(new Header("Content-Type", "application/json"));
//set default socket timeout for connection
HttpMethodParams params = method.getParams();
params.setSoTimeout(DEFAULT_SOCKET_TIMEOUT);
params.setContentCharset("UTF-8");
method.setParams(params);
if (cloud.getAccessToken() != null){
method.addRequestHeader(new Header("Authorization", "bearer " + cloud.getAccessToken().getString("access_token")));
return new ServerStatus(Status.OK_STATUS, HttpServletResponse.SC_OK);
}
JSONObject errorJSON = new JSONObject();
try {
errorJSON.put(CFProtocolConstants.V2_KEY_REGION_ID, cloud.getRegion());
errorJSON.put(CFProtocolConstants.V2_KEY_REGION_NAME, cloud.getRegionName() != null ? cloud.getRegionName() : "");
errorJSON.put(CFProtocolConstants.V2_KEY_ERROR_CODE, "CF-NotAuthenticated");
errorJSON.put(CFProtocolConstants.V2_KEY_ERROR_DESCRIPTION, "Not authenticated");
} catch (JSONException e) {
// do nothing
}
return new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_UNAUTHORIZED, "Not authenticated", errorJSON, null);
}
/**
* @return the http response code returned from the server. Response code 200 means success.
*/
public static int fastFailPing(AuthenticatedUrl url, int timeout) throws IOException
{
PingRequest pingRequest = null;
try
{
HttpClient httpClient = getHttpClient(url);
pingRequest = new PingRequest(url.getPath());
HttpMethodParams params = pingRequest.getParams();
params.setSoTimeout(timeout);
httpClient.executeMethod(pingRequest);
return pingRequest.getStatusCode();
}
finally
{
if (pingRequest != null)
{
pingRequest.releaseConnection();
}
}
}
public static Cookie[] requestNewSession(AuthenticatedUrl url)
{
CreateSessionRequest createSessionRequest = null;
try
{
HttpClient httpClient = getHttpClient(url);
createSessionRequest = new CreateSessionRequest(url.getPath());
HttpMethodParams params = createSessionRequest.getParams();
params.setSoTimeout(PING_TIMEOUT);
httpClient.executeMethod(createSessionRequest);
return httpClient.getState().getCookies();
}
catch (Exception e)
{
throw new RuntimeException("Failed to create session", e);
}
finally
{
if (createSessionRequest != null)
{
createSessionRequest.releaseConnection();
}
}
}
private void configureHttpMethod(boolean skipContentCache, CacheData cacheData, long onceTimeOut,
HttpMethod httpMethod) {
if (skipContentCache && null != cacheData) {
if (null != cacheData.getLastModifiedHeader() && Constants.NULL != cacheData.getLastModifiedHeader()) {
httpMethod.addRequestHeader(Constants.IF_MODIFIED_SINCE, cacheData.getLastModifiedHeader());
}
if (null != cacheData.getMd5() && Constants.NULL != cacheData.getMd5()) {
httpMethod.addRequestHeader(Constants.CONTENT_MD5, cacheData.getMd5());
}
}
httpMethod.addRequestHeader(Constants.ACCEPT_ENCODING, "gzip,deflate");
// 设置HttpMethod的参数
HttpMethodParams params = new HttpMethodParams();
params.setSoTimeout((int) onceTimeOut);
// ///////////////////////
httpMethod.setParams(params);
httpClient.getHostConfiguration().setHost(diamondConfigure.getDomainNameList().get(this.domainNamePos.get()),
diamondConfigure.getPort());
}
public PostRequest buildMultipartPostRequest(File file, String filename, String siteId, String containerId) throws IOException
{
Part[] parts =
{
new FilePart("filedata", file.getName(), file, "text/plain", null),
new StringPart("filename", filename),
new StringPart("description", "description"),
new StringPart("siteid", siteId),
new StringPart("containerid", containerId)
};
MultipartRequestEntity multipartRequestEntity = new MultipartRequestEntity(parts, new HttpMethodParams());
ByteArrayOutputStream os = new ByteArrayOutputStream();
multipartRequestEntity.writeRequest(os);
PostRequest postReq = new PostRequest(UPLOAD_URL, os.toByteArray(), multipartRequestEntity.getContentType());
return postReq;
}
public void post(){
String requesturl = "http://www.tuling123.com/openapi/api";
PostMethod postMethod = new PostMethod(requesturl);
String APIKEY = "4b441cb500f431adc6cc0cb650b4a5d0";
String INFO ="北京时间";
NameValuePair nvp1=new NameValuePair("key",APIKEY);
NameValuePair nvp2=new NameValuePair("info",INFO);
NameValuePair[] data = new NameValuePair[2];
data[0]=nvp1;
data[1]=nvp2;
postMethod.setRequestBody(data);
postMethod.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET,"utf-8");
try {
byte[] responseBody = executeMethod(postMethod,10000);
String content=new String(responseBody ,"utf-8");
log.info(content);
}catch (Exception e){
log.error(""+e.getLocalizedMessage());
}finally {
postMethod.releaseConnection();
}
}
/**
* 向目标发出一个Post请求并得到响应数据
* @param url
* 目标
* @param params
* 参数集合
* @param timeout
* 超时时间
* @return 响应数据
* @throws IOException
*/
public static String sendPost(String url, NameValuePair[] data, int timeout) throws Exception {
log.info("url:" + url);
PostMethod method = new PostMethod(url);
method.setRequestBody(data);
method.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "utf-8");
byte[] content;
String text = null, charset = null;
try {
content = executeMethod(method, timeout);
charset = method.getResponseCharSet();
text = new String(content, charset);
log.info("post return:" + text);
} catch (Exception e) {
throw e;
} finally {
method.releaseConnection();
}
return text;
}
private void configureHttpMethod(boolean skipContentCache, CacheData cacheData, long onceTimeOut,
HttpMethod httpMethod) {
if (skipContentCache && null != cacheData) {
if (null != cacheData.getLastModifiedHeader() && Constants.NULL != cacheData.getLastModifiedHeader()) {
httpMethod.addRequestHeader(Constants.IF_MODIFIED_SINCE, cacheData.getLastModifiedHeader());
}
if (null != cacheData.getMd5() && Constants.NULL != cacheData.getMd5()) {
httpMethod.addRequestHeader(Constants.CONTENT_MD5, cacheData.getMd5());
}
}
httpMethod.addRequestHeader(Constants.ACCEPT_ENCODING, "gzip,deflate");
// 设置HttpMethod的参数
HttpMethodParams params = new HttpMethodParams();
params.setSoTimeout((int) onceTimeOut);
// ///////////////////////
httpMethod.setParams(params);
httpClient.getHostConfiguration().setHost(diamondConfigure.getDomainNameList().get(this.domainNamePos.get()),
diamondConfigure.getPort());
}
/**
* Recycles the HTTP method so that it can be used again.
* Note that all of the instance variables will be reset
* once this method has been called. This method will also
* release the connection being used by this HTTP method.
*
* @see #releaseConnection()
*
* @deprecated no longer supported and will be removed in the future
* version of HttpClient
*/
public void recycle() {
LOG.trace("enter HttpMethodBase.recycle()");
releaseConnection();
path = null;
followRedirects = false;
doAuthentication = true;
queryString = null;
getRequestHeaderGroup().clear();
getResponseHeaderGroup().clear();
getResponseTrailerHeaderGroup().clear();
statusLine = null;
effectiveVersion = null;
aborted = false;
used = false;
params = new HttpMethodParams();
responseBody = null;
recoverableExceptionCount = 0;
connectionCloseForced = false;
hostAuthState.invalidate();
proxyAuthState.invalidate();
cookiespec = null;
requestSent = false;
}
@Test(groups = "wso2.esb", description = "Sending HTTP1.0 message")
public void sendingHTTP10Message() throws Exception {
PostMethod post = new PostMethod(getProxyServiceURLHttp("StockQuoteProxyTestHTTPVersion"));
RequestEntity entity = new StringRequestEntity(getPayload(), "text/xml", "UTF-8");
post.setRequestEntity(entity);
post.setRequestHeader("SOAPAction", "urn:getQuote");
HttpMethodParams params = new HttpMethodParams();
params.setVersion(HttpVersion.HTTP_1_0);
post.setParams(params);
HttpClient httpClient = new HttpClient();
String httpVersion = "";
try {
httpClient.executeMethod(post);
post.getResponseBodyAsString();
httpVersion = post.getStatusLine().getHttpVersion();
} finally {
post.releaseConnection();
}
Assert.assertEquals(httpVersion, HttpVersion.HTTP_1_0.toString(), "Http version mismatched");
}
@Test(groups = "wso2.esb", description = "Sending HTTP1.1 message")
public void sendingHTTP11Message() throws Exception {
PostMethod post = new PostMethod(getProxyServiceURLHttp("StockQuoteProxyTestHTTPVersion"));
RequestEntity entity = new StringRequestEntity(getPayload(), "text/xml", "UTF-8");
post.setRequestEntity(entity);
post.setRequestHeader("SOAPAction", "urn:getQuote");
HttpMethodParams params = new HttpMethodParams();
params.setVersion(HttpVersion.HTTP_1_1);
post.setParams(params);
HttpClient httpClient = new HttpClient();
String httpVersion = "";
try {
httpClient.executeMethod(post);
post.getResponseBodyAsString();
httpVersion = post.getStatusLine().getHttpVersion();
} finally {
post.releaseConnection();
}
Assert.assertEquals(httpVersion, HttpVersion.HTTP_1_1.toString(), "Http version mismatched");
}
/**
* Sets the <tt>Expect</tt> header if it has not already been set,
* in addition to the "standard" set of headers.
*
* @param state the {@link HttpState state} information associated with this method
* @param conn the {@link HttpConnection connection} used to execute
* this HTTP method
*
* @throws IOException if an I/O (transport) error occurs. Some transport exceptions
* can be recovered from.
* @throws HttpException if a protocol exception occurs. Usually protocol exceptions
* cannot be recovered from.
*/
protected void addRequestHeaders(HttpState state, HttpConnection conn)
throws IOException, HttpException {
LOG.trace("enter ExpectContinueMethod.addRequestHeaders(HttpState, HttpConnection)");
super.addRequestHeaders(state, conn);
// If the request is being retried, the header may already be present
boolean headerPresent = (getRequestHeader("Expect") != null);
// See if the expect header should be sent
// = HTTP/1.1 or higher
// = request body present
if (getParams().isParameterTrue(HttpMethodParams.USE_EXPECT_CONTINUE)
&& getEffectiveVersion().greaterEquals(HttpVersion.HTTP_1_1)
&& hasRequestContent())
{
if (!headerPresent) {
setRequestHeader("Expect", "100-continue");
}
} else {
if (headerPresent) {
removeRequestHeader("Expect");
}
}
}
/**
* Recycles the HTTP method so that it can be used again.
* Note that all of the instance variables will be reset
* once this method has been called. This method will also
* release the connection being used by this HTTP method.
*
* @see #releaseConnection()
*
* @deprecated no longer supported and will be removed in the future
* version of HttpClient
*/
public void recycle() {
LOG.trace("enter HttpMethodBase.recycle()");
releaseConnection();
path = null;
followRedirects = false;
doAuthentication = true;
queryString = null;
getRequestHeaderGroup().clear();
getResponseHeaderGroup().clear();
getResponseTrailerHeaderGroup().clear();
statusLine = null;
effectiveVersion = null;
aborted = false;
used = false;
params = new HttpMethodParams();
responseBody = null;
recoverableExceptionCount = 0;
connectionCloseForced = false;
hostAuthState.invalidate();
proxyAuthState.invalidate();
cookiespec = null;
requestSent = false;
}
@Override
public HttpClient create() {
HttpClient client = new HttpClient();
if (soTimeout >= 0) {
client.getParams().setSoTimeout(soTimeout);
}
ClassAliasResolver<HttpMethodRetryHandler> aliasResolver = new ClassAliasResolver<>(HttpMethodRetryHandler.class);
HttpMethodRetryHandler httpMethodRetryHandler;
try {
httpMethodRetryHandler = GobblinConstructorUtils.invokeLongestConstructor(aliasResolver.resolveClass(httpMethodRetryHandlerClass), httpMethodRetryCount, httpRequestSentRetryEnabled);
} catch (ReflectiveOperationException e) {
throw new RuntimeException(e);
}
client.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, httpMethodRetryHandler);
if (connTimeout >= 0) {
client.getHttpConnectionManager().getParams().setConnectionTimeout(connTimeout);
}
return client;
}
@Test
public void test() {
HttpClient client = new HttpClient();
client.getParams().setConnectionManagerTimeout(CONNECTION_TIMEOUT);
client.getParams().setSoTimeout(SO_TIMEOUT);
GetMethod method = new GetMethod(webServer.getCallHttpUrl());
// Provide custom retry handler is necessary
method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false));
method.setQueryString(new NameValuePair[] { new NameValuePair("key2", "value2") });
try {
// Execute the method.
client.executeMethod(method);
} catch (Exception ignored) {
} finally {
method.releaseConnection();
}
PluginTestVerifier verifier = PluginTestVerifierHolder.getInstance();
verifier.printCache();
}
@Test
public void hostConfig() {
HttpClient client = new HttpClient();
client.getParams().setConnectionManagerTimeout(CONNECTION_TIMEOUT);
client.getParams().setSoTimeout(SO_TIMEOUT);
HostConfiguration config = new HostConfiguration();
config.setHost("weather.naver.com", 80, "http");
GetMethod method = new GetMethod("/rgn/cityWetrMain.nhn");
// Provide custom retry handler is necessary
method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false));
method.setQueryString(new NameValuePair[] { new NameValuePair("key2", "value2") });
try {
// Execute the method.
client.executeMethod(config, method);
} catch (Exception ignored) {
} finally {
method.releaseConnection();
}
PluginTestVerifier verifier = PluginTestVerifierHolder.getInstance();
verifier.printCache();
}
public MessageResult sendMessage(String mobile, String content,SmsDTO smsDTO) throws Exception{
log.info("sms content={}", content);
HttpClient httpClient = new HttpClient();
PostMethod postMethod = new PostMethod("http://api.1cloudsp.com/api/v2/single_send");
postMethod.getParams().setContentCharset("UTF-8");
postMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());
NameValuePair[] data = {
new NameValuePair("accesskey", smsDTO.getKeyId()),
new NameValuePair("secret", smsDTO.getKeySecret()),
new NameValuePair("sign", smsDTO.getSignId()),
new NameValuePair("templateId", smsDTO.getTemplateId()),
new NameValuePair("mobile", mobile),
new NameValuePair("content", URLEncoder.encode(content, "utf-8"))//(发送的短信内容是模板变量内容,多个变量中间用##或者$$隔开,采用utf8编码)
};
postMethod.setRequestBody(data);
int statusCode = httpClient.executeMethod(postMethod);
System.out.println("statusCode: " + statusCode + ", body: "
+ postMethod.getResponseBodyAsString());
log.info(" mobile : " + mobile + "content : " + content);
log.info("statusCode: " + statusCode + ", body: "
+ postMethod.getResponseBodyAsString());
return parseResult(postMethod.getResponseBodyAsString());
}
public MessageResult sendMessage(String mobile, String content,SmsDTO smsDTO) throws Exception{
log.info("sms content={}", content);
HttpClient httpClient = new HttpClient();
PostMethod postMethod = new PostMethod("http://api.1cloudsp.com/api/v2/single_send");
postMethod.getParams().setContentCharset("UTF-8");
postMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());
NameValuePair[] data = {
new NameValuePair("accesskey", smsDTO.getKeyId()),
new NameValuePair("secret", smsDTO.getKeySecret()),
new NameValuePair("sign", smsDTO.getSignId()),
new NameValuePair("templateId", smsDTO.getTemplateId()),
new NameValuePair("mobile", mobile),
new NameValuePair("content", URLEncoder.encode(content, "utf-8"))//(发送的短信内容是模板变量内容,多个变量中间用##或者$$隔开,采用utf8编码)
};
postMethod.setRequestBody(data);
int statusCode = httpClient.executeMethod(postMethod);
System.out.println("statusCode: " + statusCode + ", body: "
+ postMethod.getResponseBodyAsString());
log.info(" mobile : " + mobile + "content : " + content);
log.info("statusCode: " + statusCode + ", body: "
+ postMethod.getResponseBodyAsString());
return parseResult(postMethod.getResponseBodyAsString());
}
/**
* Create basic http client with default params.
*
* @return HttpClient instance
*/
private static HttpClient getBaseInstance() {
HttpClient httpClient = new HttpClient();
httpClient.getParams().setParameter(HttpMethodParams.USER_AGENT, getUserAgent());
httpClient.getParams().setParameter(HttpClientParams.MAX_REDIRECTS, Settings.getIntProperty("davmail.httpMaxRedirects", MAX_REDIRECTS));
httpClient.getParams().setCookiePolicy("DavMailCookieSpec");
return httpClient;
}
public void testPropfindAddressBook() throws IOException, DavException {
DavPropertyNameSet davPropertyNameSet = new DavPropertyNameSet();
//davPropertyNameSet.add(DavPropertyName.create("getctag", Namespace.getNamespace("http://calendarserver.org/ns/")));
davPropertyNameSet.add(DavPropertyName.create("getetag", Namespace.getNamespace("DAV:")));
PropFindMethod method = new PropFindMethod("/users/" + session.getEmail()+"/addressbook/", davPropertyNameSet, 1);
httpClient.getParams().setParameter(HttpMethodParams.USER_AGENT, "Address%20Book/883 CFNetwork/454.12.4 Darwin/10.8.0 (i386) (MacBookPro3%2C1)");
httpClient.executeMethod(method);
assertEquals(HttpStatus.SC_MULTI_STATUS, method.getStatusCode());
method.getResponseBodyAsMultiStatus();
}
private static PostMethod genPostMethod(String url) {
String[] matrixInfos = ParamConfig.getAttribute(MATRIX_CALL,
"http://www.boubei.com,ANONYMOUS,0211bdae3d86730fe302940832025419").split(",");
PostMethod postMethod = new PostMethod(matrixInfos[0] + url);
postMethod.addParameter("uName", matrixInfos[1]);
postMethod.addParameter("uToken", matrixInfos[2]);
postMethod.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "utf-8");
return postMethod;
}
protected JSONObject postQuery(HttpClient httpClient, String url, JSONObject body) throws UnsupportedEncodingException,
IOException, HttpException, URIException, JSONException
{
PostMethod post = new PostMethod(url);
if (body.toString().length() > DEFAULT_SAVEPOST_BUFFER)
{
post.getParams().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, true);
}
StringRequestEntity requestEntity = new StringRequestEntity(body.toString(), "application/json", "UTF-8");
post.setRequestEntity(requestEntity);
try
{
httpClient.executeMethod(post);
if(post.getStatusCode() == HttpStatus.SC_MOVED_PERMANENTLY || post.getStatusCode() == HttpStatus.SC_MOVED_TEMPORARILY)
{
Header locationHeader = post.getResponseHeader("location");
if (locationHeader != null)
{
String redirectLocation = locationHeader.getValue();
post.setURI(new URI(redirectLocation, true));
httpClient.executeMethod(post);
}
}
if (post.getStatusCode() != HttpServletResponse.SC_OK)
{
throw new LuceneQueryParserException("Request failed " + post.getStatusCode() + " " + url.toString());
}
Reader reader = new BufferedReader(new InputStreamReader(post.getResponseBodyAsStream(), post.getResponseCharSet()));
// TODO - replace with streaming-based solution e.g. SimpleJSON ContentHandler
JSONObject json = new JSONObject(new JSONTokener(reader));
return json;
}
finally
{
post.releaseConnection();
}
}
public static HttpClient getHttpClient(AuthenticatedUrl url)
{
HttpClient httpClient = new HttpClient(HTTP_CONNECTION_MANAGER);
httpClient.getHostConfiguration().setHost(url.getHost(), url.getPort());
httpClient.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, NoRetryRetryHandler.getInstance());
url.setCredentialsOnClient(httpClient);
return httpClient;
}
public PostRequest buildMultipartPostRequest(File file) throws IOException
{
Part[] parts = { new FilePart("filedata", file.getName(), file, "application/zip", null) };
MultipartRequestEntity multipartRequestEntity = new MultipartRequestEntity(parts, new HttpMethodParams());
ByteArrayOutputStream os = new ByteArrayOutputStream();
multipartRequestEntity.writeRequest(os);
PostRequest postReq = new PostRequest(UPLOAD_URL, os.toByteArray(), multipartRequestEntity.getContentType());
return postReq;
}
/**
* post请求
*
* @param paramMap 请求参数
* @param requestUrl 请求地址
* @return
*/
private static Map<String, Object> request(SortedMap<String, String> paramMap, String requestUrl) {
logger.info("鉴权请求地址:[{}],请求参数:[{}]", requestUrl, paramMap);
HttpClient httpClient = new HttpClient();
HttpConnectionManagerParams managerParams = httpClient.getHttpConnectionManager().getParams();
// 设置连接超时时间(单位毫秒)
managerParams.setConnectionTimeout(9000);
// 设置读数据超时时间(单位毫秒)
managerParams.setSoTimeout(12000);
PostMethod postMethod = new PostMethod(requestUrl);
postMethod.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "utf-8");
NameValuePair[] pairs = new NameValuePair[paramMap.size()];
int i = 0;
for (Map.Entry<String, String> entry : paramMap.entrySet()) {
pairs[i++] = new NameValuePair(entry.getKey(), entry.getValue());
}
postMethod.setRequestBody(pairs);
try {
Integer code = httpClient.executeMethod(postMethod);
if (code.compareTo(200) == 0) {
String result = postMethod.getResponseBodyAsString();
logger.info("鉴权请求成功,同步返回数据:{}", result);
return JSON.parseObject(result);
} else {
logger.error("鉴权请求失败,返回状态码:[{}]", code);
}
} catch (IOException e) {
logger.info("鉴权请求异常:{}", e);
return null;
}
return null;
}