@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(); } }
/** * 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"); } } }
public String doPut(String url, String charset, String jsonObj) { String resStr = null; HttpClient htpClient = new HttpClient(); PutMethod putMethod = new PutMethod(url); putMethod.getParams().setParameter( HttpMethodParams.HTTP_CONTENT_CHARSET, charset); try { putMethod.setRequestEntity(new StringRequestEntity(jsonObj, "application/json", charset)); int statusCode = htpClient.executeMethod(putMethod); if (statusCode != HttpStatus.SC_OK) { log.error("Method failed: " + putMethod.getStatusLine()); return null; } byte[] responseBody = putMethod.getResponseBody(); resStr = new String(responseBody, charset); } catch (Exception e) { e.printStackTrace(); } finally { putMethod.releaseConnection(); } return resStr; }
/** * @return the http response code returned from the server. Response code 200 means success. */ public static int fastFailPing(AuthenticatedUrl url) throws IOException { PingRequest pingRequest = null; try { HttpClient httpClient = getHttpClient(url); pingRequest = new PingRequest(url.getPath()); HttpMethodParams params = pingRequest.getParams(); params.setSoTimeout(PING_TIMEOUT); httpClient.executeMethod(pingRequest); return pingRequest.getStatusCode(); } finally { if (pingRequest != null) { pingRequest.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 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(); } } }
@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 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; }
@SuppressWarnings("unchecked") private HttpMethod createGetMethod(HttpServletRequest req, String uri) throws ServletException, NotLoggedInException { GetMethod get = new GetMethod(uri); addUserNameToHeader(get, req); addAcceptEncodingHeader(get, req); get.getParams().setContentCharset("UTF-8"); HttpMethodParams params = new HttpMethodParams(); Enumeration e = req.getParameterNames(); while (e.hasMoreElements()) { String paramName = (String) e.nextElement(); for (String value : req.getParameterValues(paramName)) { params.setParameter(paramName, value); } } get.setParams(params); return get; }
@SuppressWarnings("unchecked") private HttpMethod createDeleteMethod(HttpServletRequest req, String redirectUrl) throws IOException, ServletException, NotLoggedInException { DeleteMethod delete = new DeleteMethod(redirectUrl); addUserNameToHeader(delete, req); addAcceptEncodingHeader(delete, req); delete.getParams().setContentCharset("UTF-8"); HttpMethodParams params = new HttpMethodParams(); Enumeration e = req.getParameterNames(); while (e.hasMoreElements()) { String paramName = (String) e.nextElement(); String[] values = req.getParameterValues(paramName); for (String value : values) { params.setParameter(paramName, value); } } delete.setParams(params); return delete; }
/** * 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; }
/** * Tests if client is able to recover gracefully when HTTP server or * proxy fails to send 100 status code when expected. The client should * resume sending the request body after a defined timeout without having * received "continue" code. */ public void testNoncompliantPostMethodString() throws Exception { this.server.setRequestHandler(new HttpRequestHandler() { public boolean processRequest(SimpleHttpServerConnection conn, SimpleRequest request) throws IOException { ResponseWriter out = conn.getWriter(); out.println("HTTP/1.1 200 OK"); out.println("Connection: close"); out.println("Content-Length: 0"); out.println(); out.flush(); return true; } }); PostMethod method = new PostMethod("/"); method.getParams().setBooleanParameter( HttpMethodParams.USE_EXPECT_CONTINUE, true); method.setRequestEntity(new StringRequestEntity( "This is data to be sent in the body of an HTTP POST.", null, null)); client.executeMethod(method); assertEquals(200, method.getStatusCode()); }
/** * Test if a response to HEAD method from non-compliant server that contains * an unexpected body content can be correctly redirected */ public void testNoncompliantHeadWithResponseBody() throws Exception { final String body = "Test body"; this.server.setRequestHandler(new HttpRequestHandler() { public boolean processRequest(SimpleHttpServerConnection conn, SimpleRequest request) throws IOException { ResponseWriter out = conn.getWriter(); out.println("HTTP/1.1 200 OK"); out.println("Connection: close"); out.println("Content-Length: " + body.length()); out.println(); out.print(body); out.flush(); return true; } }); HeadMethod method = new HeadMethod("/"); method.getParams().setIntParameter( HttpMethodParams.HEAD_BODY_CHECK_TIMEOUT, 50); client.executeMethod(method); assertEquals(200, method.getStatusCode()); method.releaseConnection(); }
public static String getPostResponseHeader(String url,String argJson,List<UHeader> headerList,String headerName){ String info = ""; try { HttpClient client = new HttpClient(); PostMethod method = new PostMethod(url); client.getParams().setContentCharset("UTF-8"); if(headerList.size()>0){ for(int i = 0;i<headerList.size();i++){ UHeader header = headerList.get(i); method.setRequestHeader(header.getHeaderTitle(),header.getHeaderValue()); } } method.getParams().setParameter( HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8"); if(argJson != null && !argJson.trim().equals("")) { RequestEntity requestEntity = new StringRequestEntity(argJson,"application/json","UTF-8"); method.setRequestEntity(requestEntity); } method.releaseConnection(); Header h = method.getResponseHeader(headerName); info = h.getValue(); } catch (IOException e) { e.printStackTrace(); } return info; }
/** * 发送一个post请求 * * @param url 地址 * @param params 参数 * @return 返回结果 * @throws java.io.IOException */ public static String post(String url, Map<String, String> params) throws IOException { PostMethod method = new PostMethod(url); method.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, DEFAULT_CHARSET); method.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, DEFAULT_TIMEOUT); if (MapUtils.isNotEmpty(params)) { List<NameValuePair> pairs = new ArrayList<>(params.size()); for (Map.Entry<String, String> entry : params.entrySet()) { NameValuePair pair = new NameValuePair(); pair.setName(entry.getKey()); pair.setValue(entry.getValue()); pairs.add(pair); } method.addParameters(pairs.toArray(new NameValuePair[pairs.size()])); } return executeMethod(method); }
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; }
/** * 发短信 * * @param apikey apikey * @param text 短信内容 * @param mobile 接受的手机号 * @return json格式字符串 * @throws IOException */ public static String sendSms(String apikey, String text, String mobile){ HttpClient client = new HttpClient(); NameValuePair[] nameValuePairs = new NameValuePair[3]; nameValuePairs[0] = new NameValuePair("apikey", apikey); nameValuePairs[1] = new NameValuePair("text", text); nameValuePairs[2] = new NameValuePair("mobile", mobile); PostMethod method = new PostMethod(URI_SEND_SMS); method.setRequestBody(nameValuePairs); HttpMethodParams param = method.getParams(); param.setContentCharset(ENCODING); try { client.executeMethod(method); return method.getResponseBodyAsString(); } catch (IOException ex) { throw new RuntimeException("sendSms error", ex); } finally { method.releaseConnection(); HttpConnectionManager connectionManager = client.getHttpConnectionManager(); ((SimpleHttpConnectionManager)connectionManager).shutdown(); } }
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 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); }
public static String debugHttpMethod(HttpMethod method) { StringBuffer stringBuffer = new StringBuffer(); stringBuffer.append("\nName:"); stringBuffer.append(method.getName()); stringBuffer.append("\n"); stringBuffer.append("\nPath:"); stringBuffer.append(method.getPath()); stringBuffer.append("\n"); stringBuffer.append("\nQueryString:"); stringBuffer.append(method.getQueryString()); stringBuffer.append("\n"); stringBuffer.append("\nUri:"); try { stringBuffer.append(method.getURI().toString()); } catch (URIException e) { // Do nothing } stringBuffer.append("\n"); HttpMethodParams httpMethodParams = method.getParams(); stringBuffer.append("\nHttpMethodParams:"); stringBuffer.append(httpMethodParams.toString()); return stringBuffer.toString(); }
@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 boolean davPut(File upload, String toPath) { try { PutMethod put = new PutMethod(getResourceUrl(toPath)); RequestEntity requestEntity = new InputStreamRequestEntity(new BufferedInputStream( new FileInputStream(upload), HttpServices.BUFFER_SIZE), upload.length()); put.setRequestEntity(requestEntity); /** is to allow a client that is sending a request message with a request body * to determine if the origin server is willing to accept the request * (based on the request headers) before the client sends the request body. * this require server supporting HTTP/1.1 protocol. */ put.getParams().setBooleanParameter( HttpMethodParams.USE_EXPECT_CONTINUE, true); if (!executeMethod(put)) { // handle error System.out.println("Unable to upload file:" + toPath + " -- " + put.getStatusText()); return false; } return true; } catch (Exception e) { LOG.error(e, "Error while uploading file:" + upload.getPath()); } return false; }
/** * @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); } }
public Response post(String url, PostParameter[] params, Boolean WithTokenHeader, PostParameter[] headers) throws MxException { PostMethod postMethod = new PostMethod(url); for (int i = 0; i < params.length; i++) { String pValue = params[i].getValue(); if (pValue != null) { postMethod.addParameter(params[i].getName(), params[i].getValue()); } } HttpMethodParams param = postMethod.getParams(); param.setContentCharset("UTF-8"); if (WithTokenHeader) { return httpRequest(postMethod, headers); } else { return httpRequest(postMethod, WithTokenHeader, headers, null); } }
/** * Define client configuration * @param httpClient instance to configure */ private static void setConfiguration(final HttpClient httpClient) { final HttpConnectionManagerParams httpParams = httpClient.getHttpConnectionManager().getParams(); // define connect timeout: httpParams.setConnectionTimeout(NetworkSettings.DEFAULT_CONNECT_TIMEOUT); // define read timeout: httpParams.setSoTimeout(NetworkSettings.DEFAULT_SOCKET_READ_TIMEOUT); // define connection parameters: httpParams.setMaxTotalConnections(NetworkSettings.DEFAULT_MAX_TOTAL_CONNECTIONS); httpParams.setDefaultMaxConnectionsPerHost(NetworkSettings.DEFAULT_MAX_HOST_CONNECTIONS); // set content-encoding to UTF-8 instead of default ISO-8859 final HttpClientParams httpClientParams = httpClient.getParams(); // define timeout value for allocation of connections from the pool httpClientParams.setConnectionManagerTimeout(NetworkSettings.DEFAULT_CONNECT_TIMEOUT); // encoding to UTF-8 httpClientParams.setParameter(HttpClientParams.HTTP_CONTENT_CHARSET, "UTF-8"); // avoid retries (3 by default): httpClientParams.setParameter(HttpMethodParams.RETRY_HANDLER, _httpNoRetryHandler); // Customize the user agent: httpClientParams.setParameter(HttpMethodParams.USER_AGENT, System.getProperty(NetworkSettings.PROPERTY_USER_AGENT)); }
@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; }
/** * Tests if client is able to recover gracefully when HTTP server or * proxy fails to send 100 status code when expected. The client should * resume sending the request body after a defined timeout without having * received "continue" code. */ public void testNoncompliantPostMethodString() throws Exception { this.server.setRequestHandler(new HttpRequestHandler() { public boolean processRequest(SimpleHttpServerConnection conn, SimpleRequest request) throws IOException { ResponseWriter out = conn.getWriter(); out.println("HTTP/1.1 200 OK"); out.println("Connection: close"); out.println("Content-Length: 0"); out.println(); out.flush(); return true; } }); PostMethod method = new PostMethod("/"); method.getParams().setBooleanParameter( HttpMethodParams.USE_EXPECT_CONTINUE, true); method.setRequestEntity(new StringRequestEntity( "This is data to be sent in the body of an HTTP POST.")); client.executeMethod(method); assertEquals(200, method.getStatusCode()); }