@Override public HttpResponse get(URL urlObj, String userName, String password, int timeout) { HttpClient client = new HttpClient(); HttpMethod method = new GetMethod(urlObj.toString()); client.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler()); client.getParams().setSoTimeout(1000 * timeout); client.getParams().setConnectionManagerTimeout(1000 * timeout); if (userName != null && password != null) { setBasicAuthorization(method, userName, password); } try { int response = client.executeMethod(method); return new HttpResponse(response, method.getResponseBody()); } catch (IOException e) { throw new RuntimeException("Failed to get " + urlObj.toString(), e); } finally { method.releaseConnection(); } }
@Override public HttpResponse post(URL urlObj, byte[] payload, String userName, String password, int timeout) { HttpClient client = new HttpClient(); PostMethod method = new PostMethod(urlObj.toString()); method.setRequestEntity(new ByteArrayRequestEntity(payload)); method.setRequestHeader("Content-type", "application/json"); client.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler()); client.getParams().setSoTimeout(1000 * timeout); client.getParams().setConnectionManagerTimeout(1000 * timeout); if (userName != null && password != null) { setBasicAuthorization(method, userName, password); } try { int response = client.executeMethod(method); return new HttpResponse(response, method.getResponseBody()); } catch (IOException e) { throw new RuntimeException("Failed to process post request URL: " + urlObj, e); } finally { method.releaseConnection(); } }
private PostMethod createPostMethod(KalturaParams kparams, KalturaFiles kfiles, String url) { PostMethod method = new PostMethod(url); method.setRequestHeader("Accept","text/xml,application/xml,*/*"); method.setRequestHeader("Accept-Charset","utf-8,ISO-8859-1;q=0.7,*;q=0.5"); if (!kfiles.isEmpty()) { method = this.getPostMultiPartWithFiles(method, kparams, kfiles); } else { method = this.addParams(method, kparams); } if (isAcceptGzipEncoding()) { method.addRequestHeader(HTTP_HEADER_ACCEPT_ENCODING, ENCODING_GZIP); } // Provide custom retry handler is necessary method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler (3, false)); return method; }
public static void main(String[] args) throws Exception { HttpClient hc = new HttpClient(); PostMethod method = null; //同步企业名录 method = new PostMethod("http://test.vop.onlyou.com/interface/bpo/UserValidate.htm"); JSONObject jsonObject = new JSONObject(); jsonObject.put("username", "pancs_qd"); jsonObject.put("password", "123456"); String transJson = jsonObject.toString(); RequestEntity se = new StringRequestEntity(transJson,"application/json","UTF-8"); method.setRequestEntity(se); //使用系统提供的默认的恢复策略 method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler()); //设置超时的时间 method.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 3000); int statusCode = hc.executeMethod(method); System.out.println(statusCode); byte[] responseBody = method.getResponseBody(); System.out.println(new String(responseBody)); System.out.println("getStatusLine:"+method.getStatusLine()); String response = new String(method.getResponseBodyAsString().getBytes("utf-8")); System.out.println("response:"+response); }
public void getCustomerList() throws JSONException, IOException { HttpClient hc = new HttpClient(); PostMethod method = null; JSONObject jsonObject = new JSONObject(); System.out.println("同步企业名录"); method = new PostMethod("http://test.vop.onlyou.com/interface/bpo/getCustomerList.htm"); jsonObject.put("lastSyncDate", "201501"); String transJson = jsonObject.toString(); RequestEntity se = new StringRequestEntity(transJson,"application/json","UTF-8"); method.setRequestEntity(se); //使用系统提供的默认的恢复策略 method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler()); //设置超时的时间 method.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 3000); hc.executeMethod(method); InputStream strStream = method.getResponseBodyAsStream(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); int i=-1; while((i=strStream.read())!=-1){ baos.write(i); } String strBody = baos.toString(); System.out.println(new String(strBody)); System.out.println("getStatusLine:"+method.getStatusLine()); }
public void UserValidate() throws JSONException, IOException { HttpClient hc = new HttpClient(); PostMethod method = null; System.out.println(" 扫描前置客户端权限校验"); method = new PostMethod("http://test.vop.onlyou.com/interface/bpo/UserValidate.htm"); JSONObject jsonObject = new JSONObject(); jsonObject.put("username", "pancs_qd"); jsonObject.put("password", "111111"); String transJson = jsonObject.toString(); RequestEntity se = new StringRequestEntity(transJson,"application/json","UTF-8"); method.setRequestEntity(se); //使用系统提供的默认的恢复策略 method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler()); //设置超时的时间 method.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 3000); hc.executeMethod(method); InputStream strStream = method.getResponseBodyAsStream(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); int i=-1; while((i=strStream.read())!=-1){ baos.write(i); } String strBody = baos.toString(); System.out.println(new String(strBody)); System.out.println("getStatusLine:"+method.getStatusLine()); }
public static void main(String[] args) throws Exception { HttpClient hc = new HttpClient(); PostMethod method = null; JSONObject jsonObject = new JSONObject(); //同步企业名录 method = new PostMethod("http://test.vop.onlyou.com/interface/bpo/getCustomerList.htm"); jsonObject.put("lastSyncDate", "201501"); String transJson = jsonObject.toString(); RequestEntity se = new StringRequestEntity(transJson,"application/json","UTF-8"); method.setRequestEntity(se); //使用系统提供的默认的恢复策略 method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler()); //设置超时的时间 method.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 3000); int statusCode = hc.executeMethod(method); System.out.println(statusCode); byte[] responseBody = method.getResponseBody(); System.out.println(new String(responseBody)); System.out.println("getStatusLine:"+method.getStatusLine()); String response = new String(method.getResponseBodyAsString().getBytes("utf-8")); System.out.println("response:"+response); }
/** * @param martServiceLocation * @param data * @return * @throws MartServiceException */ private static InputStream executeMethod(HttpMethod method, String martServiceLocation) throws MartServiceException { HttpClient client = new HttpClient(); if (isProxyHost(martServiceLocation)) { setProxy(client); } method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false)); // method.getParams().setSoTimeout(60000); try { int statusCode = client.executeMethod(method); if (statusCode != HttpStatus.SC_OK) { throw constructException(method, martServiceLocation, null); } return method.getResponseBodyAsStream(); } catch (IOException e) { throw constructException(method, martServiceLocation, e); } }
@Test public void test() throws Exception { 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() throws Exception { 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(); }
private static HttpClient getHttpClient() { HttpClient httpClient = new HttpClient(); // 设置 HttpClient 接收 Cookie,用与浏览器一样的策略 httpClient.getParams().setCookiePolicy( CookiePolicy.BROWSER_COMPATIBILITY); // 设置 默认的超时重试处理策略 httpClient.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler()); // 设置 连接超时时间 httpClient.getHttpConnectionManager().getParams() .setConnectionTimeout(TIMEOUT_CONNECTION); // 设置 读数据超时时间 httpClient.getHttpConnectionManager().getParams() .setSoTimeout(TIMEOUT_SOCKET); // 设置 字符集 httpClient.getParams().setContentCharset(UTF_8); return httpClient; }
/** * 获取HttpClient对象 * * @return */ private static HttpClient getHttpClient() { HttpClient httpClient = new HttpClient(); // 设置 HttpClient 接收 Cookie,用与浏览器一样的策略 httpClient.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY); // 设置 默认的超时重试处理策略 httpClient.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler()); // 设置 连接超时时间 httpClient.getHttpConnectionManager().getParams() .setConnectionTimeout(TIMEOUT_CONNECTION); // 设置 读数据超时时间 httpClient.getHttpConnectionManager().getParams().setSoTimeout(TIMEOUT_SOCKET); // 设置 字符集 httpClient.getParams().setContentCharset(UTF_8); return httpClient; }
private static HttpClient getHttpClient() { HttpClient httpClient = new HttpClient(); httpClient.getParams().setCookiePolicy( CookiePolicy.BROWSER_COMPATIBILITY); httpClient.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler()); httpClient.getHttpConnectionManager().getParams() .setConnectionTimeout(TIMEOUT_CONNECTION); httpClient.getHttpConnectionManager().getParams().setParameter("http.socket.timeout", TIMEOUT_SOCKET); httpClient.getHttpConnectionManager().getParams() .setSoTimeout(TIMEOUT_SOCKET); httpClient.getParams().setContentCharset(UTF_8); return httpClient; }
private HttpMethod executeQuery(FederatedSearch sruSearch, String query, SRUSettings settings, int offset, int perpage) throws IOException { HttpMethod httpMethod = null; try { // URL includes the port (if any) we trust ... URL url = new URL(settings.getUrl()); PostMethod postMethod = new PostMethod(url.toExternalForm()); NameValuePair[] nameValuePairs = populateNameValuePairs(query, settings, offset, perpage); postMethod.addParameters(nameValuePairs); httpMethod = postMethod; } catch( Exception e ) { throw new RuntimeException(e); } HttpClient httpClient = new HttpClient(); httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(sruSearch.getTimeout() * 1000); httpClient.getHttpConnectionManager().getParams().setSoTimeout(sruSearch.getTimeout() * 1000); // Prevent the default 3 tries - so once is enough ...? httpClient.getHttpConnectionManager().getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(0, false)); httpClient.executeMethod(httpMethod); return httpMethod; }
/** * Builds an HTTP client with the given settings. Settings are NOT reset to their default values after a client has * been created. * * @return the created client. */ public HttpClient buildClient() { if (httpsProtocolSocketFactory != null) { Protocol.registerProtocol("https", new Protocol("https", httpsProtocolSocketFactory, 443)); } HttpClientParams clientParams = new HttpClientParams(); clientParams.setAuthenticationPreemptive(isPreemptiveAuthentication()); clientParams.setContentCharset(getContentCharSet()); clientParams.setParameter(HttpClientParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler( connectionRetryAttempts, false)); HttpConnectionManagerParams connMgrParams = new HttpConnectionManagerParams(); connMgrParams.setConnectionTimeout(getConnectionTimeout()); connMgrParams.setDefaultMaxConnectionsPerHost(getMaxConnectionsPerHost()); connMgrParams.setMaxTotalConnections(getMaxTotalConnections()); connMgrParams.setReceiveBufferSize(getReceiveBufferSize()); connMgrParams.setSendBufferSize(getSendBufferSize()); connMgrParams.setTcpNoDelay(isTcpNoDelay()); MultiThreadedHttpConnectionManager connMgr = new MultiThreadedHttpConnectionManager(); connMgr.setParams(connMgrParams); HttpClient httpClient = new HttpClient(clientParams, connMgr); if (proxyHost != null) { HostConfiguration hostConfig = new HostConfiguration(); hostConfig.setProxy(proxyHost, proxyPort); httpClient.setHostConfiguration(hostConfig); if (proxyUsername != null) { AuthScope proxyAuthScope = new AuthScope(proxyHost, proxyPort); UsernamePasswordCredentials proxyCredentials = new UsernamePasswordCredentials(proxyUsername, proxyPassword); httpClient.getState().setProxyCredentials(proxyAuthScope, proxyCredentials); } } return httpClient; }
@Test public void noBillsF() throws JSONException, IOException { HttpClient hc = new HttpClient(); PostMethod method = null; JSONObject jsonObject = new JSONObject(); ////////////////////////////////////////// //设置url以及json参数: method = new PostMethod("http://test.vop.onlyou.com/interface/bpo/noBills.htm"); jsonObject.put("customerCode", "ffd92cf3256f464f973deccca5435c3e"); jsonObject.put("date","201508"); ////////////////////////////////////////// String transJson = jsonObject.toString(); System.out.println(transJson); RequestEntity se = new StringRequestEntity(transJson,"application/json","UTF-8"); method.setRequestEntity(se); //使用系统提供的默认的恢复策略 method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler()); //设置超时的时间 method.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 3000); hc.executeMethod(method); InputStream strStream = method.getResponseBodyAsStream(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); int i=-1; while((i=strStream.read())!=-1){ baos.write(i); } String strBody = baos.toString(); System.out.println(new String(strBody)); System.out.println("getStatusLine:"+method.getStatusLine()); }
public void noBills() throws JSONException, IOException { HttpClient hc = new HttpClient(); PostMethod method = null; JSONObject jsonObject = new JSONObject(); ////////////////////////////////////////// System.out.println("无票通知"); //设置url以及json参数: method = new PostMethod("http://test.vop.onlyou.com/interface/bpo/noBills.htm"); jsonObject.put("customerCode", "ffd92cf3256f464f973deccca5435c3e"); jsonObject.put("date","201508"); ////////////////////////////////////////// String transJson = jsonObject.toString(); System.out.println(transJson); RequestEntity se = new StringRequestEntity(transJson,"application/json","UTF-8"); method.setRequestEntity(se); //使用系统提供的默认的恢复策略 method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler()); //设置超时的时间 method.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 3000); hc.executeMethod(method); InputStream strStream = method.getResponseBodyAsStream(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); int i=-1; while((i=strStream.read())!=-1){ baos.write(i); } String strBody = baos.toString(); System.out.println(new String(strBody)); System.out.println("getStatusLine:"+method.getStatusLine()); }
@Test public void scanningFinished() throws JSONException, IOException { HttpClient hc = new HttpClient(); PostMethod method = null; JSONObject jsonObject = new JSONObject(); System.out.println("票据已扫描完毕"); //设置url以及json参数: method = new PostMethod("http://test.vop.onlyou.com/interface/bpo/scanningFinished.htm"); jsonObject.put("customerCode", "39ed0cef1a0c4b69b2b55ab95e089490"); jsonObject.put("date","201603"); jsonObject.put("billsCount", "3549"); jsonObject.put("path","/bills/086240201_2/1468679728809/201603/V204000023_3"); String transJson = jsonObject.toString(); System.out.println(transJson); //String transJson1 ="{\"billsCount\":\"5\",\"customerCode\":\"937a6c26f8e04f4d941e9dc12d7b7536\",\"path\":\"/bills/1004/1474613050035/201602/V241000018\",\"date\":\"201602\"}"; //System.out.println(transJson1); RequestEntity se = new StringRequestEntity(transJson,"application/json","UTF-8"); method.setRequestEntity(se); //使用系统提供的默认的恢复策略 method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler()); //设置超时的时间 method.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 3000); hc.executeMethod(method); InputStream strStream = method.getResponseBodyAsStream(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); int i=-1; while((i=strStream.read())!=-1){ baos.write(i); } String strBody = baos.toString(); System.out.println(new String(strBody)); System.out.println("getStatusLine:"+method.getStatusLine()); }
public void billFinished() throws JSONException, IOException { HttpClient hc = new HttpClient(); PostMethod method = null; JSONObject jsonObject = new JSONObject(); System.out.println("传票完毕通知"); //设置url以及json参数: method = new PostMethod("http://test.vop.onlyou.com/interface/bpo/billFinished.htm"); jsonObject.put("billsCount", "3549"); jsonObject.put("customerCode", "39ed0cef1a0c4b69b2b55ab95e089490"); jsonObject.put("path","/bills/086240201_2/1468679728809/201603/V204000023_3"); jsonObject.put("date","201603"); String transJson = jsonObject.toString(); System.out.println(transJson); //String transJson1 ="{\"billsCount\":\"5\",\"customerCode\":\"937a6c26f8e04f4d941e9dc12d7b7536\",\"path\":\"/bills/1004/1474613050035/201602/V241000018\",\"date\":\"201602\"}"; //System.out.println(transJson1); RequestEntity se = new StringRequestEntity(transJson,"application/json","UTF-8"); method.setRequestEntity(se); //使用系统提供的默认的恢复策略 method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler()); //设置超时的时间 method.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 3000); hc.executeMethod(method); InputStream strStream = method.getResponseBodyAsStream(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); int i=-1; while((i=strStream.read())!=-1){ baos.write(i); } String strBody = baos.toString(); System.out.println(new String(strBody)); System.out.println("getStatusLine:"+method.getStatusLine()); }
public static void main(String[] args) throws Exception { HttpClient hc = new HttpClient(); PostMethod method = null; JSONObject jsonObject = new JSONObject(); //设置url以及json参数: method = new PostMethod("http://test.vop.onlyou.com/interface/bpo/billFinished.htm"); jsonObject.put("billsCount", "5"); jsonObject.put("customerCode", "937a6c26f8e04f4d941e9dc12d7b7536"); jsonObject.put("path","/bills/1004/1474613050035/201602/V241000018"); jsonObject.put("date","201602"); String transJson = jsonObject.toString(); System.out.println(transJson); //String transJson1 ="{\"billsCount\":\"5\",\"customerCode\":\"937a6c26f8e04f4d941e9dc12d7b7536\",\"path\":\"/bills/1004/1474613050035/201602/V241000018\",\"date\":\"201602\"}"; //System.out.println(transJson1); RequestEntity se = new StringRequestEntity(transJson,"application/json","UTF-8"); method.setRequestEntity(se); //使用系统提供的默认的恢复策略 method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler()); //设置超时的时间 method.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 3000); hc.executeMethod(method); byte[] responseBody = method.getResponseBody(); System.out.println(new String(responseBody)); System.out.println("getStatusLine:"+method.getStatusLine()); String response = new String(method.getResponseBodyAsString().getBytes("utf-8")); System.out.println("response:"+response); }
private static HttpClient getHttpClient() { HttpClient httpClient = new HttpClient(); // 设置 HttpClient 接收 Cookie,用与浏览器一样的策略 httpClient.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY); // 设置 默认的超时重试处理策略 httpClient.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler()); // 设置 连接超时时间 httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(TIMEOUT_CONNECTION); // 设置 读数据超时时间 httpClient.getHttpConnectionManager().getParams().setSoTimeout(TIMEOUT_SOCKET); // 设置 字符集 httpClient.getParams().setContentCharset(UTF_8); return httpClient; }
public static HttpClient createHttpClient() { HttpClient result = null; try { result = new HttpClient(); // 使用多緒HttpClient MultiThreadedHttpConnectionManager httpConnectionManager = new MultiThreadedHttpConnectionManager(); HttpConnectionManagerParams managerParams = httpConnectionManager .getParams(); managerParams.setDefaultMaxConnectionsPerHost(100); managerParams.setMaxTotalConnections(200); // 連線超時 managerParams.setConnectionTimeout(5 * 1000); // 讀取超時 managerParams.setSoTimeout(5 * 1000); // result.setHttpConnectionManager(httpConnectionManager); // HttpClientParams params = result.getParams(); // http.protocol.content-charset params.setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8"); // 失敗 retry 3 次 params.setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false)); } catch (Exception ex) { ex.printStackTrace(); } return result; }
public static void main(String[] args) { HttpClient httpclient; String url; GetMethod method; ProtocolSocketFactory fcty; url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wxd30e31bfd8c207ee&secret=d0f9c44269c0282a1a7337efea1950a1"; //https 证书 fcty = new MySecureProtocolSocketFactory(); Protocol.registerProtocol("https", new Protocol("https", fcty, 443)); httpclient = new HttpClient(); method = new GetMethod(url);// get调用 method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false)); try { int statusCode = httpclient.executeMethod(method); if (statusCode != HttpStatus.SC_OK) { System.out.println(statusCode + ": " + method.getStatusLine()); } else { System.out.println(new String(method.getResponseBody(), "UTF-8")); } } catch (IOException e) { e.printStackTrace(); } finally { method.releaseConnection(); } }
private static HttpClient getHttpClient() { HttpClient httpClient = new HttpClient(); // 设置默认的超时重试处理策略 httpClient.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler()); // 设置连接超时时间 httpClient.getHttpConnectionManager().getParams() .setConnectionTimeout(TIMEOUT_CONNECTION); httpClient.getParams().setContentCharset(UTF_8); return httpClient; }
private InputStream getInputStreamFromGetMethod(GetMethod get, int timeout) throws Exception { get.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(0, false)); HttpClient httpClient = new HttpClient(); httpClient.getParams().setParameter(HttpClientParams.SO_TIMEOUT, new Integer(timeout)); httpClient.getParams().setParameter(HttpClientParams.CONNECTION_MANAGER_TIMEOUT, new Long(timeout)); httpClient.getParams().setParameter(HttpConnectionParams.CONNECTION_TIMEOUT, new Integer(timeout)); int status = httpClient.executeMethod(get); if (status == HttpStatus.OK.value()) { return get.getResponseBodyAsStream(); } return null; }
public void ensureInitialized() throws GeocoderException { if (m_geocoder == null) { if (notEmpty(m_clientId) && notEmpty(m_clientKey)) { try { LOG.info("Initializing Google Geocoder using Client ID and Key."); m_geocoder = new AdvancedGeoCoder(m_clientId, m_clientKey); } catch (final InvalidKeyException e) { throw new GeocoderException("Unable to initialize Google Geocoder.", e); } } if (m_geocoder == null) { LOG.info("Initializing Google Geocoder using default configuration."); m_geocoder = new AdvancedGeoCoder(); } final HttpClient httpClient = m_geocoder.getHttpClient(); /* Configure proxying, if necessary... */ final String httpProxyHost = System.getProperty("http.proxyHost"); final Integer httpProxyPort = Integer.getInteger("http.proxyPort"); if (httpProxyHost != null && httpProxyPort != null) { LOG.info("Proxy configuration found, using {}:{} as HTTP proxy.", httpProxyHost, httpProxyPort); httpClient.getHostConfiguration().setProxy(httpProxyHost, httpProxyPort); } else { LOG.info("No proxy configuration found."); } /* Limit retries... */ httpClient.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(1, true)); LOG.info("Google Geocoder initialized."); } }
/** * Open an HTTP GET method connection to a URL and read the returned response into an * object. * * @param url * remote URL (usually a web service's URL) * @param httpMethod * HTTP method * @return <code>HttpClient</code> {@link HttpMethod} transfer object, containing the * response headers and body */ public static HttpResponseTo getHttpResponse(final String url, final HttpMethod method) { if (log.isDebugEnabled()) { log.debug("Sending HTTP " + method + " request to " + url); } // Create an instance of HttpClient. final HttpClient client = new HttpClient(); // Create a method instance. // Provide custom retry handler is necessary method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(NUMBER_HTTP_REQUEST_TRIALS, false)); try { // Execute the method final int statusCode = client.executeMethod(method); if (statusCode >= 400) { log.error("Method failed: " + method.getStatusLine()); } return new HttpResponseTo(method); } catch (final Throwable e) { if (log.isInfoEnabled()) { log.info("Failed to receive HTTP request from " + url + ": " + e.getMessage()); } } return null; }
/** * @param url * @return */ private static HttpMethod newGetMethod(final String url) { final HttpMethod method = new GetMethod(url); // Provide custom retry handler is necessary method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(NUMBER_HTTP_REQUEST_TRIALS, false)); return method; }
static HttpClient getHttpClient() { HttpClient httpClient = new HttpClient(); // 设置 HttpClient 接收 Cookie,用与浏览器一样的策略 httpClient.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY); // 设置 默认的超时重试处理策略 httpClient.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler()); // 设置 连接超时时间 httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(TIMEOUT_CONNECTION); // 设置 读数据超时时间 httpClient.getHttpConnectionManager().getParams().setSoTimeout(TIMEOUT_SOCKET); // 设置 字符集 httpClient.getParams().setContentCharset(UTF_8); return httpClient; }
/** * This function does the SEND http communication to the device * */ public Integer sendDataToService(String service, byte[] data) { // Create an instance of HttpClient. Integer rCode = null; if (client == null) { client = new HttpClient(); } synchronized (client) { // Create a method instance. PostMethod method = new PostMethod("http://" + device.getIP4Address() + service); // Provide custom retry handler is necessary method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false)); // Set the right header method.setRequestHeader("Accept", "application/json"); method.addRequestHeader("User-Agent", "TeleHeater/2.2.3"); method.setRequestEntity(new ByteArrayRequestEntity(data)); try { rCode = client.executeMethod(method); } catch (Exception e) { logger.error("Failed to send data {}", e); } finally { // Release the connection. method.releaseConnection(); } return rCode; } }
public static boolean contactServer(String s, String URI, StringBuffer response) { HttpClient client = new HttpClient(); GetMethod method = new GetMethod(URI); NameValuePair[] pairs = new NameValuePair[1]; pairs[0] = new NameValuePair("build", StringEscapeUtils.escapeHtml3("\t" + s + "\tOS =\t" + System.getProperty("os.name") + "\t" + System.getProperty("os.version") + "\tjava =\t" + System.getProperty("java.version") +"\t" + System.getProperty("java.vendor"))); method.setQueryString(pairs); method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false)); return executeMethod(client, method, response); }
public static boolean postToServer(String s, String URI, StringBuffer response) { HttpClient client = new HttpClient(); PostMethod method = new PostMethod(URI); method.addParameter("OS", StringEscapeUtils.escapeHtml3(System.getProperty("os.name") + "\t" + System.getProperty("os.version"))); method.addParameter("JVM", StringEscapeUtils.escapeHtml3(System.getProperty("java.version") +"\t" + System.getProperty("java.vendor"))); NameValuePair post = new NameValuePair(); post.setName("post"); post.setValue(StringEscapeUtils.escapeHtml3(s)); method.addParameter(post); method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false)); return executeMethod(client, method, response); }
public static boolean sendInfoToServer(NameValuePair[] pairs, String URI, StringBuffer response, int retryCount) { HttpClient client = new HttpClient(); GetMethod method = new GetMethod(URI); method.setQueryString(pairs); // if (retryCount>0) method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(retryCount, false)); return executeMethod(client, method, response); }
public static void main(String[] args) throws Exception { //新的创建httpClient的方法 CloseableHttpClient httpclient = HttpClients.createDefault(); HttpClient hc = new HttpClient(); try { HttpGet httpGet = new HttpGet("http://test.vop.onlyou.com/interface/bpo/getCustomerList.htm"); CloseableHttpResponse response1 = httpclient.execute(httpGet); // The underlying HTTP connection is still held by the response object // to allow the response content to be streamed directly from the network socket. // In order to ensure correct deallocation of system resources // the user MUST call CloseableHttpResponse#close() from a finally clause. // Please note that if response content is not fully consumed the underlying // connection cannot be safely re-used and will be shut down and discarded // by the connection manager. try { System.out.println(response1.getStatusLine()); HttpEntity entity1 = response1.getEntity(); // do something useful with the response body // and ensure it is fully consumed EntityUtils.consume(entity1); } finally { response1.close(); } PostMethod method = null; //同步企业名录 //method = new PostMethod("http://test.vop.onlyou.com/interface/bpo/getCustomerList.htm"); method = new PostMethod("http://test.vop.onlyou.com/interface/bpo/UserValidate.htm"); JSONObject jsonObject = new JSONObject(); // jsonObject.put("lastSyncDate", "201501"); jsonObject.put("username", "pancs_qd"); jsonObject.put("password", "123456"); String transJson = jsonObject.toString(); RequestEntity se = new StringRequestEntity(transJson,"application/json","UTF-8"); method.setRequestEntity(se); //使用系统提供的默认的恢复策略 method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler()); //设置超时的时间 method.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 3000); int statusCode = hc.executeMethod(method); System.out.println(statusCode); byte[] responseBody = method.getResponseBody(); System.out.println(new String(responseBody)); System.out.println("getStatusLine:"+method.getStatusLine()); String response = new String(method.getResponseBodyAsString().getBytes("utf-8")); System.out.println("response:"+response); //httpPostWithJSON("http://test.vop.onlyou.com/interface/bpo/getCustomerList.htm",strJson); //httpPostWithJSON("http://test.vop.onlyou.com/interface/bpo/billFinished.htm","{'billsCount':1,'customerCode':'66c84403d7b949b4ad70377ac87b360c','path':'/bills/086240201_2/9568679728809/201601/V204200022','date':'201601'}"); /* HttpPost httpPost = new HttpPost("http://test.vop.onlyou.com:80/interface/bpo/billFinished.htm"); httpPost.addHeader("Content-Type", "application/json"); List <NameValuePair> nvps = new ArrayList <NameValuePair>(); nvps.add(new BasicNameValuePair("billsCount", "1")); nvps.add(new BasicNameValuePair("customerCode", "66c84403d7b949b4ad70377ac87b360c")); nvps.add(new BasicNameValuePair("path","/bills/086240201_2/9568679728809/201601/V204200022")); nvps.add(new BasicNameValuePair("date","201601")); httpPost.setEntity(new UrlEncodedFormEntity(nvps)); CloseableHttpResponse response2 = httpclient.execute(httpPost); try { System.out.println(response2.getStatusLine()); HttpEntity entity2 = response2.getEntity(); // do something useful with the response body // and ensure it is fully consumed EntityUtils.consume(entity2); } finally { response2.close(); }*/ } finally { httpclient.close(); } }
public Response httpRequest(HttpMethod method, Boolean WithTokenHeader, String token) throws WeiboException { InetAddress ipaddr; int responseCode = -1; try { ipaddr = InetAddress.getLocalHost(); List<Header> headers = new ArrayList<Header>(); if (WithTokenHeader) { if (token == null) { throw new IllegalStateException("Oauth2 token is not set!"); } headers.add(new Header("Authorization", "OAuth2 " + token)); headers.add(new Header("API-RemoteIP", ipaddr.getHostAddress())); client.getHostConfiguration().getParams() .setParameter("http.default-headers", headers); for (Header hd : headers) { log(hd.getName() + ": " + hd.getValue()); } } method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false)); client.executeMethod(method); Header[] resHeader = method.getResponseHeaders(); responseCode = method.getStatusCode(); log("Response:"); log("https StatusCode:" + String.valueOf(responseCode)); for (Header header : resHeader) { log(header.getName() + ":" + header.getValue()); } Response response = new Response(); response.setResponseAsString(method.getResponseBodyAsString()); log(response.toString() + "\n"); if (responseCode != OK) { try { throw new WeiboException(getCause(responseCode), response.asJSONObject(), method.getStatusCode()); } catch (JSONException e) { e.printStackTrace(); } } return response; } catch (IOException ioe) { throw new WeiboException(ioe.getMessage(), ioe, responseCode); } finally { method.releaseConnection(); } }
@SetEnvironment(executionEnvironments = {ExecutionEnvironment.STANDALONE}) @Test(groups = {"wso2.esb"}, description = "Patch : ESBJAVA-1696 : Encoded Special characters in the URL is decoded at the Gateway and not re-encoded", enabled = true) public void testEncodingSpecialCharacterViaHttpProxy() throws IOException { HttpClient client = new HttpClient(); client.getParams().setParameter( HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(0, false)); client.getParams().setSoTimeout(5000); client.getParams().setConnectionManagerTimeout(5000); // Create POST method String url = getProxyServiceURLHttp("MyProxy"); PostMethod method = new PostMethod(url); // Set parameters on POST String value1 = "Hello World"; String value2 = "This is a Form Submission containing %"; String value3 = URLEncoder.encode("This is an encoded value containing %"); method.setParameter("test1", value1); method.addParameter("test2", value2); method.addParameter("test3", value3); // Execute and print response try { client.executeMethod(method); } catch (Exception e) { } finally { method.releaseConnection(); } String response = wireMonitorServer.getCapturedMessage(); String[] responseArray = response.split("test"); if (responseArray.length < 3) { Assert.fail("All attributes are not sent"); } for (String res : responseArray) { if (res.startsWith("1")) { Assert.assertTrue(res.startsWith("1=" + URLEncoder.encode(value1).replace("+", "%20"))); } else if (res.startsWith("2")) { Assert.assertTrue(res.startsWith("2=" + URLEncoder.encode(value2).replace("+", "%20"))); } else if (res.startsWith("3")) { Assert.assertTrue(res.startsWith("3=" + URLEncoder.encode(value3))); } } }