Java tutorial
/* * Copyright 2016-2017 Shanghai Boyuan IT Services Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.boyuanitsm.pay.alipay.util.httpClient; import org.apache.commons.httpclient.*; import org.apache.commons.httpclient.methods.GetMethod; import org.apache.commons.httpclient.methods.PostMethod; import org.apache.commons.httpclient.methods.multipart.*; import org.apache.commons.httpclient.params.HttpMethodParams; import org.apache.commons.httpclient.util.IdleConnectionTimeoutThread; import java.io.File; import java.io.IOException; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.List; /* * *??HttpProtocolHandler *HttpClient? *?HTTP? *3.3 *2012-08-17 * *????????,??? *??????? */ public class HttpProtocolHandler { private static String DEFAULT_CHARSET = "GBK"; /** bean factory?8 */ private int defaultConnectionTimeout = 8000; /** , bean factory?30 */ private int defaultSoTimeout = 30000; /** , bean factory?60 */ private int defaultIdleConnTimeout = 60000; private int defaultMaxConnPerHost = 30; private int defaultMaxTotalConn = 80; /** HttpConnectionManager?1*/ private static final long defaultHttpConnectionManagerTimeout = 3 * 1000; /** * HTTP??. */ private HttpConnectionManager connectionManager; private static HttpProtocolHandler httpProtocolHandler = new HttpProtocolHandler(); /** * * * @return */ public static HttpProtocolHandler getInstance() { return httpProtocolHandler; } /** * ? */ private HttpProtocolHandler() { // HTTP connectionManager = new MultiThreadedHttpConnectionManager(); connectionManager.getParams().setDefaultMaxConnectionsPerHost(defaultMaxConnPerHost); connectionManager.getParams().setMaxTotalConnections(defaultMaxTotalConn); IdleConnectionTimeoutThread ict = new IdleConnectionTimeoutThread(); ict.addConnectionManager(connectionManager); ict.setConnectionTimeout(defaultIdleConnTimeout); ict.start(); } /** * Http * * @param request ? * @param strParaFileName ??? * @param strFilePath * @return * @throws HttpException, IOException */ public HttpResponse execute(HttpRequest request, String strParaFileName, String strFilePath) throws HttpException, IOException { HttpClient httpclient = new HttpClient(connectionManager); // int connectionTimeout = defaultConnectionTimeout; if (request.getConnectionTimeout() > 0) { connectionTimeout = request.getConnectionTimeout(); } httpclient.getHttpConnectionManager().getParams().setConnectionTimeout(connectionTimeout); // int soTimeout = defaultSoTimeout; if (request.getTimeout() > 0) { soTimeout = request.getTimeout(); } httpclient.getHttpConnectionManager().getParams().setSoTimeout(soTimeout); // ConnectionManagerconnection httpclient.getParams().setConnectionManagerTimeout(defaultHttpConnectionManagerTimeout); String charset = request.getCharset(); charset = charset == null ? DEFAULT_CHARSET : charset; HttpMethod method = null; //get?? if (request.getMethod().equals(HttpRequest.METHOD_GET)) { method = new GetMethod(request.getUrl()); method.getParams().setCredentialCharset(charset); // parseNotifyConfig??GETrequestQueryString method.setQueryString(request.getQueryString()); } else if (strParaFileName.equals("") && strFilePath.equals("")) { //post?? method = new PostMethod(request.getUrl()); ((PostMethod) method).addParameters(request.getParameters()); method.addRequestHeader("Content-Type", "application/x-www-form-urlencoded; text/html; charset=" + charset); } else { //post? method = new PostMethod(request.getUrl()); List<Part> parts = new ArrayList<Part>(); for (int i = 0; i < request.getParameters().length; i++) { parts.add(new StringPart(request.getParameters()[i].getName(), request.getParameters()[i].getValue(), charset)); } //?strParaFileName??? parts.add(new FilePart(strParaFileName, new FilePartSource(new File(strFilePath)))); // ((PostMethod) method).setRequestEntity( new MultipartRequestEntity(parts.toArray(new Part[0]), new HttpMethodParams())); } // Http HeaderUser-Agent method.addRequestHeader("User-Agent", "Mozilla/4.0"); HttpResponse response = new HttpResponse(); try { httpclient.executeMethod(method); if (request.getResultType().equals(HttpResultType.STRING)) { response.setStringResult(method.getResponseBodyAsString()); } else if (request.getResultType().equals(HttpResultType.BYTES)) { response.setByteResult(method.getResponseBody()); } response.setResponseHeaders(method.getResponseHeaders()); } catch (UnknownHostException ex) { return null; } catch (IOException ex) { return null; } catch (Exception ex) { return null; } finally { method.releaseConnection(); } return response; } /** * NameValuePairs? * * @param nameValues * @return */ protected String toString(NameValuePair[] nameValues) { if (nameValues == null || nameValues.length == 0) { return "null"; } StringBuffer buffer = new StringBuffer(); for (int i = 0; i < nameValues.length; i++) { NameValuePair nameValue = nameValues[i]; if (i == 0) { buffer.append(nameValue.getName() + "=" + nameValue.getValue()); } else { buffer.append("&" + nameValue.getName() + "=" + nameValue.getValue()); } } return buffer.toString(); } }