org.apache.commons.httpclient.params.HttpMethodParams Java Examples

The following examples show how to use org.apache.commons.httpclient.params.HttpMethodParams. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ESBJAVA4846HttpProtocolVersionTestCase.java    From micro-integrator with Apache License 2.0 6 votes vote down vote up
@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");
}
 
Example #2
Source File: DefaultDiamondSubscriber.java    From diamond with Apache License 2.0 6 votes vote down vote up
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());
}
 
Example #3
Source File: HttpMethodBase.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * 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;
}
 
Example #4
Source File: HttpClientUtil.java    From javabase with Apache License 2.0 6 votes vote down vote up
/**
 * 向目标发出一个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;
}
 
Example #5
Source File: OldHttpClientApi.java    From javabase with Apache License 2.0 6 votes vote down vote up
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();
    }
}
 
Example #6
Source File: ExpectContinueMethod.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * 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");
        }
    }
}
 
Example #7
Source File: UploadWebScriptTest.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 6 votes vote down vote up
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;
}
 
Example #8
Source File: DefaultDiamondSubscriber.java    From diamond with Apache License 2.0 6 votes vote down vote up
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());
}
 
Example #9
Source File: HttpMessageTransport.java    From jrpip with Apache License 2.0 6 votes vote down vote up
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();
        }
    }
}
 
Example #10
Source File: HttpMethodBase.java    From http4e with Apache License 2.0 6 votes vote down vote up
/**
 * 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;
}
 
Example #11
Source File: HttpMessageTransport.java    From jrpip with Apache License 2.0 6 votes vote down vote up
/**
 * @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();
        }
    }
}
 
Example #12
Source File: HttpUtil.java    From orion.server with Eclipse Public License 1.0 6 votes vote down vote up
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);
}
 
Example #13
Source File: ESBJAVA4846HttpProtocolVersionTestCase.java    From product-ei with Apache License 2.0 6 votes vote down vote up
@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");

}
 
Example #14
Source File: AbstractTest4.java    From boubei-tss with Apache License 2.0 6 votes vote down vote up
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);
    }
}
 
Example #15
Source File: HttpClientFactory.java    From incubator-gobblin with Apache License 2.0 6 votes vote down vote up
@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;
}
 
Example #16
Source File: ESBJAVA4846HttpProtocolVersionTestCase.java    From product-ei with Apache License 2.0 6 votes vote down vote up
@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");
}
 
Example #17
Source File: HttpClientIT.java    From pinpoint with Apache License 2.0 6 votes vote down vote up
@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();
}
 
Example #18
Source File: HttpClientIT.java    From pinpoint with Apache License 2.0 6 votes vote down vote up
@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();
}
 
Example #19
Source File: HttpUtil.java    From OfficeAutomatic-System with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example #20
Source File: HttpUtil.java    From OfficeAutomatic-System with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example #21
Source File: APIFactory.java    From wpcleaner with Apache License 2.0 5 votes vote down vote up
/**
 * Create an HTTP connection.
 * 
 * @return A HTTP connection.
 */
private static HttpClient createHttpClient(HttpConnectionManager manager) {
  HttpClient client = new HttpClient(manager);
  client.getParams().setParameter(
      HttpMethodParams.USER_AGENT,
      "WPCleaner (+http://en.wikipedia.org/wiki/User:NicoV/Wikipedia_Cleaner/Documentation)");
  return client;
}
 
Example #22
Source File: NetClient.java    From qingyang with Apache License 2.0 5 votes vote down vote up
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;
}
 
Example #23
Source File: ESBJAVA4846HttpProtocolVersionTestCase.java    From micro-integrator with Apache License 2.0 5 votes vote down vote up
@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");

}
 
Example #24
Source File: HttpMethodBase.java    From http4e with Apache License 2.0 5 votes vote down vote up
/**
 * A response has been consumed.
 *
 * <p>The default behavior for this class is to check to see if the connection
 * should be closed, and close if need be, and to ensure that the connection
 * is returned to the connection manager - if and only if we are not still
 * inside the execute call.</p>
 *
 */
protected void responseBodyConsumed() {

    // make sure this is the initial invocation of the notification,
    // ignore subsequent ones.
    responseStream = null;
    if (responseConnection != null) {
        responseConnection.setLastResponseInputStream(null);

        // At this point, no response data should be available.
        // If there is data available, regard the connection as being
        // unreliable and close it.
        
        if (shouldCloseConnection(responseConnection)) {
            responseConnection.close();
        } else {
            try {
                if(responseConnection.isResponseAvailable()) {
                    boolean logExtraInput =
                        getParams().isParameterTrue(HttpMethodParams.WARN_EXTRA_INPUT);

                    if(logExtraInput) {
                        LOG.warn("Extra response data detected - closing connection");
                    } 
                    responseConnection.close();
                }
            }
            catch (IOException e) {
                LOG.warn(e.getMessage());
                responseConnection.close();
            }
        }
    }
    this.connectionCloseForced = false;
    ensureConnectionRelease();
}
 
Example #25
Source File: BaseHttpRequestMaker.java    From MesquiteCore with GNU Lesser General Public License v3.0 5 votes vote down vote up
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);
}
 
Example #26
Source File: HeadMethod.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Overrides {@link HttpMethodBase} method to <i>not</i> read a response
 * body, despite the presence of a <tt>Content-Length</tt> or
 * <tt>Transfer-Encoding</tt> header.
 * 
 * @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.
 *
 * @see #readResponse
 * @see #processResponseBody
 * 
 * @since 2.0
 */
protected void readResponseBody(HttpState state, HttpConnection conn)
throws HttpException, IOException {
    LOG.trace(
        "enter HeadMethod.readResponseBody(HttpState, HttpConnection)");
    
    int bodyCheckTimeout = 
        getParams().getIntParameter(HttpMethodParams.HEAD_BODY_CHECK_TIMEOUT, -1);

    if (bodyCheckTimeout < 0) {
        responseBodyConsumed();
    } else {
        if (LOG.isDebugEnabled()) {
            LOG.debug("Check for non-compliant response body. Timeout in " 
             + bodyCheckTimeout + " ms");    
        }
        boolean responseAvailable = false;
        try {
            responseAvailable = conn.isResponseAvailable(bodyCheckTimeout);
        } catch (IOException e) {
            LOG.debug("An IOException occurred while testing if a response was available,"
                + " we will assume one is not.", 
                e);
            responseAvailable = false;
        }
        if (responseAvailable) {
            if (getParams().isParameterTrue(HttpMethodParams.REJECT_HEAD_BODY)) {
                throw new ProtocolException(
                    "Body content may not be sent in response to HTTP HEAD request");
            } else {
                LOG.warn("Body content returned in response to HTTP HEAD");    
            }
            super.readResponseBody(state, conn);
        }
    }

}
 
Example #27
Source File: HttpMethodDirector.java    From http4e with Apache License 2.0 5 votes vote down vote up
/**
 * Applies connection parameters specified for a given method
 * 
 * @param method HTTP method
 * 
 * @throws IOException if an I/O occurs setting connection parameters 
 */
private void applyConnectionParams(final HttpMethod method) throws IOException {
    int timeout = 0;
    // see if a timeout is given for this method
    Object param = method.getParams().getParameter(HttpMethodParams.SO_TIMEOUT);
    if (param == null) {
        // if not, use the default value
        param = this.conn.getParams().getParameter(HttpConnectionParams.SO_TIMEOUT);
    }
    if (param != null) {
        timeout = ((Integer)param).intValue();
    }
    this.conn.setSocketTimeout(timeout);                    
}
 
Example #28
Source File: MultipartRequestEntity.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Returns the MIME boundary string that is used to demarcate boundaries of
 * this part. The first call to this method will implicitly create a new
 * boundary string. To create a boundary string first the 
 * HttpMethodParams.MULTIPART_BOUNDARY parameter is considered. Otherwise 
 * a random one is generated.
 * 
 * @return The boundary string of this entity in ASCII encoding.
 */
protected byte[] getMultipartBoundary() {
    if (multipartBoundary == null) {
        String temp = (String) params.getParameter(HttpMethodParams.MULTIPART_BOUNDARY);
        if (temp != null) {
            multipartBoundary = EncodingUtil.getAsciiBytes(temp);
        } else {
            multipartBoundary = generateMultipartBoundary();
        }
    }
    return multipartBoundary;
}
 
Example #29
Source File: MultipartRequestEntity.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Creates a new multipart entity containing the given parts.
 * @param parts The parts to include.
 * @param params The params of the HttpMethod using this entity.
 */
public MultipartRequestEntity(Part[] parts, HttpMethodParams params) {
    if (parts == null) {
        throw new IllegalArgumentException("parts cannot be null");
    }
    if (params == null) {
        throw new IllegalArgumentException("params cannot be null");
    }
    this.parts = parts;
    this.params = params;
}
 
Example #30
Source File: HttpMethodCloner.java    From http4e with Apache License 2.0 5 votes vote down vote up
private static void copyHttpMethodBase(
  HttpMethodBase m, HttpMethodBase copy) {
    try {
        copy.setParams((HttpMethodParams)m.getParams().clone());
    } catch (CloneNotSupportedException e) {
        // Should never happen
    }
}