Java Code Examples for org.apache.http.client.methods.HttpRequestBase#setConfig()

The following examples show how to use org.apache.http.client.methods.HttpRequestBase#setConfig() . 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: HttpClientAdapter.java    From uyuni with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Take a request as {@link HttpMethod} and execute it.
 *
 * @param request the {@link HttpMethod} to be executed
 * @param ignoreNoProxy set true to ignore the "no_proxy" setting
 * @return the return code of the request
 * @throws IOException in case of errors
 */
public HttpResponse executeRequest(HttpRequestBase request, boolean ignoreNoProxy)
        throws IOException {
    if (log.isDebugEnabled()) {
        log.debug(request.getMethod() + " " + request.getURI());
    }
    // Decide if a proxy should be used for this request

    HttpContext httpContxt = new BasicHttpContext();
    httpContxt.setAttribute(IGNORE_NO_PROXY, ignoreNoProxy);

    httpContxt.setAttribute(REQUEST_URI, request.getURI());

    // Execute the request
    request.setConfig(requestConfig);
    HttpResponse httpResponse = httpClient.execute(request, httpContxt);

    if (log.isDebugEnabled()) {
        log.debug("Response code: " + httpResponse.getStatusLine().getStatusCode());
    }
    return httpResponse;
}
 
Example 2
Source File: HttpWebConnection.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
private void setProxy(final HttpRequestBase httpRequest, final WebRequest webRequest) {
    final InetAddress localAddress = webClient_.getOptions().getLocalAddress();
    final RequestConfig.Builder requestBuilder = createRequestConfigBuilder(getTimeout(), localAddress);

    if (webRequest.getProxyHost() != null) {
        final HttpHost proxy = new HttpHost(webRequest.getProxyHost(), webRequest.getProxyPort());
        if (webRequest.isSocksProxy()) {
            SocksConnectionSocketFactory.setSocksProxy(getHttpContext(), proxy);
        }
        else {
            requestBuilder.setProxy(proxy);
            httpRequest.setConfig(requestBuilder.build());
        }
    }
    else {
        requestBuilder.setProxy(null);
        httpRequest.setConfig(requestBuilder.build());
    }
}
 
Example 3
Source File: HttpUtilManager.java    From zheshiyigeniubidexiangmu with MIT License 5 votes vote down vote up
public String requestHttpGet(String url_prex, String url, String param) throws HttpException, IOException {

		IdleConnectionMonitor();
		url = url_prex + url;
		if (param != null && !param.equals("")) {
			if (url.endsWith("?")) {
				url = url + param;
			} else {
				url = url + "?" + param;
			}
		}
		HttpRequestBase method = this.httpGetMethod(url);
		method.setConfig(requestConfig);
		HttpResponse response = client.execute(method);

		HttpEntity entity = response.getEntity();
		if (entity == null) {
			return "";
		}
		InputStream is = null;
		String responseData = "";
		try {
			is = entity.getContent();
			responseData = IOUtils.toString(is, "UTF-8");
		} finally {
			if (is != null) {
				is.close();
			}
		}
		// System.out.println(responseData);
		return responseData;
	}
 
Example 4
Source File: ApacheHttpStack.java    From jus with Apache License 2.0 5 votes vote down vote up
@Override
public NetworkResponse performRequest(Request<?> request, Headers additionalHeaders,
                                      ByteArrayPool byteArrayPool) throws IOException {
    HttpRequestBase httpRequest = createHttpRequest(request, additionalHeaders.toMap());
    addHeaders(httpRequest, additionalHeaders.toMap());
    if (request.getHeaders() != null) {
        addHeaders(httpRequest, request.getHeaders().toMap());
    }
    RequestConfig requestConfig = org.apache.http.client.config.RequestConfig.custom()
            .setSocketTimeout(request.getRetryPolicy().getCurrentReadTimeout())
            .setConnectTimeout(request.getRetryPolicy().getCurrentConnectTimeout())
            .build();
    httpRequest.setConfig(requestConfig);
    onPrepareRequest(httpRequest);
    long requestStart = System.nanoTime();
    HttpResponse response = client.execute(httpRequest, httpContext);
    byte[] data = null;
    if (NetworkDispatcher.hasResponseBody(request.getMethod(), response.getStatusLine()
            .getStatusCode())) {
        data = getContentBytes(response.getEntity().getContent(),
                byteArrayPool, (int) response.getEntity().getContentLength());

    } else {
        // Add 0 byte response as a way of honestly representing a
        // no-content request.
        data = new byte[0];
    }
    return new NetworkResponse.Builder()
            .setHeaders(JusApache.jusHeaders(response.getAllHeaders()))
            .setStatusCode(response.getStatusLine().getStatusCode())
            .setBody(data)
            .setNetworkTimeNs(System.nanoTime() - requestStart)
            .build();
}
 
Example 5
Source File: HttpActivityExecutor.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
protected void setConfig(final HttpRequestBase base, final HttpRequest requestInfo, int socketTimeout, int connectTimeout, int connectionRequestTimeout) {
    base.setConfig(RequestConfig.custom()
            .setRedirectsEnabled(!requestInfo.isNoRedirects())
            .setSocketTimeout(requestInfo.getTimeout() == 0 ? socketTimeout : requestInfo.getTimeout())
            .setConnectTimeout(connectTimeout)
            .setConnectionRequestTimeout(connectionRequestTimeout)
            .build());
}
 
Example 6
Source File: MPRestClient.java    From dx-java with MIT License 5 votes vote down vote up
private HttpRequestBase createHttpRequest(HttpMethod httpMethod, String uri, PayloadType payloadType, JsonObject payload, MPRequestOptions requestOptions) throws MPRestException {
    HttpEntity entity = normalizePayload(payloadType, payload);
    HttpRequestBase request = getRequestMethod(httpMethod, uri, entity);

    Map<String, String> headers = new HashMap<String, String>();
    headers.put(HTTP.USER_AGENT, String.format("MercadoPago Java SDK/%s", MercadoPago.SDK.getVersion()));
    headers.put("x-product-id", MercadoPago.SDK.getProductId());
    headers.put("x-tracking-id", MercadoPago.SDK.getTrackingId());
    for (String headerName : requestOptions.getCustomHeaders().keySet()) {
        if (!headers.containsKey(headerName)) {
            headers.put(headerName, requestOptions.getCustomHeaders().get(headerName));
        }
    }
    for (Map.Entry<String, String> header : headers.entrySet()) {
        request.addHeader(new BasicHeader(header.getKey(), header.getValue()));
    }

    if (payloadType == PayloadType.JSON) {
        request.addHeader(new BasicHeader(HTTP.CONTENT_TYPE, ContentType.APPLICATION_JSON.toString()));
    } else if (payloadType == PayloadType.X_WWW_FORM_URLENCODED) {
        request.addHeader(new BasicHeader(HTTP.CONTENT_TYPE, ContentType.APPLICATION_FORM_URLENCODED.toString()));
    }

    RequestConfig.Builder requestConfigBuilder = RequestConfig.custom()
            .setSocketTimeout(requestOptions.getSocketTimeout())
            .setConnectTimeout(requestOptions.getConnectionTimeout())
            .setConnectionRequestTimeout(requestOptions.getConnectionRequestTimeout());

    HttpHost proxy = httpProxy == null ? MercadoPago.SDK.getProxy() : httpProxy;
    if (proxy != null) {
        requestConfigBuilder.setProxy(proxy);
    }

    request.setConfig(requestConfigBuilder.build());
    return request;
}
 
Example 7
Source File: ApacheHttpRequestFactory.java    From ibm-cos-sdk-java with Apache License 2.0 5 votes vote down vote up
private void addRequestConfig(final HttpRequestBase base,
                              final Request<?> request,
                              final HttpClientSettings settings) {
    final RequestConfig.Builder requestConfigBuilder = RequestConfig
            .custom()
            .setConnectionRequestTimeout(settings.getConnectionPoolRequestTimeout())
            .setConnectTimeout(settings.getConnectionTimeout())
            .setSocketTimeout(settings.getSocketTimeout())
            .setLocalAddress(settings.getLocalAddress());

    ApacheUtils.disableNormalizeUri(requestConfigBuilder);

    /*
     * Enable 100-continue support for PUT operations, since this is
     * where we're potentially uploading large amounts of data and want
     * to find out as early as possible if an operation will fail. We
     * don't want to do this for all operations since it will cause
     * extra latency in the network interaction.
     */
    if (HttpMethodName.PUT == request.getHttpMethod() && settings.isUseExpectContinue()) {
        requestConfigBuilder.setExpectContinueEnabled(true);
    }

    addProxyConfig(requestConfigBuilder, settings);

    base.setConfig(requestConfigBuilder.build());
}
 
Example 8
Source File: ApacheHttpRequestFactory.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
private void addRequestConfig(final HttpRequestBase base,
                              final SdkHttpRequest request,
                              final ApacheHttpRequestConfig requestConfig) {
    int connectTimeout = saturatedCast(requestConfig.connectionTimeout().toMillis());
    int connectAcquireTimeout = saturatedCast(requestConfig.connectionAcquireTimeout().toMillis());
    RequestConfig.Builder requestConfigBuilder = RequestConfig
            .custom()
            .setConnectionRequestTimeout(connectAcquireTimeout)
            .setConnectTimeout(connectTimeout)
            .setSocketTimeout(saturatedCast(requestConfig.socketTimeout().toMillis()))
            .setLocalAddress(requestConfig.localAddress());

    ApacheUtils.disableNormalizeUri(requestConfigBuilder);

    /*
     * Enable 100-continue support for PUT operations, since this is
     * where we're potentially uploading large amounts of data and want
     * to find out as early as possible if an operation will fail. We
     * don't want to do this for all operations since it will cause
     * extra latency in the network interaction.
     */
    if (SdkHttpMethod.PUT == request.method() && requestConfig.expectContinueEnabled()) {
        requestConfigBuilder.setExpectContinueEnabled(true);
    }

    base.setConfig(requestConfigBuilder.build());
}
 
Example 9
Source File: AsuraCommonsHttpclient.java    From AsuraFramework with Apache License 2.0 5 votes vote down vote up
/**
 * @param connectTimeout
 * @param socketTimeout
 * @param httpRequestBase
 */
private void handlerRequestConfig(int connectTimeout, int socketTimeout, HttpRequestBase httpRequestBase) {
    RequestConfig requestConfig = RequestConfig.custom()
            .setConnectionRequestTimeout(connectTimeout)
            .setConnectTimeout(connectTimeout)
            .setSocketTimeout(socketTimeout).build();
    httpRequestBase.setConfig(requestConfig);
}
 
Example 10
Source File: HttpUtilManager.java    From zheshiyigeniubidexiangmu with MIT License 5 votes vote down vote up
public String requestHttpGet(String url_prex,String url,String param) throws HttpException, IOException{

		IdleConnectionMonitor();
		url=url_prex+url;
		if(param!=null && !param.equals("")){
		        if(url.endsWith("?")){
			    url = url+param;
			}else{
			    url = url+"?"+param;
			}
		}
		HttpRequestBase method = this.httpGetMethod(url);
		method.setConfig(requestConfig);
		HttpResponse response = client.execute(method);
		HttpEntity entity =  response.getEntity();
		if(entity == null){
			return "";
		}
		InputStream is = null;
		String responseData = "";
		try{
		    is = entity.getContent();
		    responseData = IOUtils.toString(is, "UTF-8");
		}finally{
			if(is!=null){
			    is.close();
			}
		}
		return responseData;
	}
 
Example 11
Source File: HttpClientUtil.java    From feiqu-opensource with Apache License 2.0 5 votes vote down vote up
public static CloseableHttpResponse getResponse(HttpRequestBase request) throws IOException {
        if (request.getConfig() == null){
            request.setConfig(requestConfig);
        }
        request.setHeader("User-Agent", CommonConstant.userAgentArray[new Random().nextInt(CommonConstant.userAgentArray.length)]);
        HttpClientContext httpClientContext = HttpClientContext.create();
        httpClientContext.setCookieStore(cookieStore);
        CloseableHttpResponse response = httpClient.execute(request, httpClientContext);
//		int statusCode = response.getStatusLine().getStatusCode();
//		if(statusCode != 200){
//			throw new IOException("status code is:" + statusCode);
//		}
        return response;
    }
 
Example 12
Source File: HttpUtilManager.java    From zheshiyigeniubidexiangmu with MIT License 5 votes vote down vote up
public HttpResponse getResponse(String url) throws ClientProtocolException, IOException {
	IdleConnectionMonitor();
	HttpRequestBase method = this.httpGetMethod(url);

	method.setConfig(requestConfig);
	HttpResponse response = client.execute(method);
	return response;
}
 
Example 13
Source File: AbstractSingleCheckThread.java    From sitemonitoring-production with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private CloseableHttpResponse doRequest(final HttpRequestBase request) throws IOException {
	if (log.isDebugEnabled()) {
		log.debug(request.getMethod() + " " + request.getURI());
	}
	Builder requestConfigBuilder = RequestConfig.custom().setSocketTimeout(check.getSocketTimeout()).setConnectTimeout(check.getConnectionTimeout());
	if (check.getHttpProxyServer() != null && !check.getHttpProxyServer().isEmpty()) {
		HttpHost httpProxy = new HttpHost(check.getHttpProxyServer(), check.getHttpProxyPort());
		requestConfigBuilder.setProxy(httpProxy);
	}
	RequestConfig requestConfig = requestConfigBuilder.build();
	request.setConfig(requestConfig);
       String header = check.getHeader();

       if(null!=header && header.length()>0 && header.contains(":"))
       {
           log.info("header:" + header);
           String[] headerKV = header.split(":");
           request.setHeader(headerKV[0],headerKV[1]);
       }

	CloseableHttpResponse response = null;
	try {
		request.setHeader("User-Agent", check.getUserAgent());
		response = httpClient.execute(request);
	} catch (SSLHandshakeException ex) {
		// ignore ValidatorException -> thrown when Java cannot validate
		// certificate
		log.error("java could not validate certificate for URL: " + request.getURI(), ex);
		return null;
	}
	if (log.isDebugEnabled()) {
		log.debug("status: " + response.getStatusLine());
	}
	return response;
}
 
Example 14
Source File: HttpUtilManager.java    From zheshiyigeniubidexiangmu with MIT License 5 votes vote down vote up
public String requestHttpGet(String url_prex, String url, String param) throws HttpException, IOException {

		IdleConnectionMonitor();
		url = url_prex + url;
		if (param != null && !param.equals("")) {
			if (url.endsWith("?")) {
				url = url + param;
			} else {
				url = url + "?" + param;
			}
		}
		HttpRequestBase method = this.httpGetMethod(url);
		method.setConfig(requestConfig);
		HttpResponse response = client.execute(method);

		HttpEntity entity = response.getEntity();
		if (entity == null) {
			return "";
		}
		InputStream is = null;
		String responseData = "";
		try {
			is = entity.getContent();
			responseData = IOUtils.toString(is, "UTF-8");
		} finally {
			if (is != null) {
				is.close();
			}
		}
		// System.out.println(responseData);
		return responseData;
	}
 
Example 15
Source File: HttpUtilManager.java    From zheshiyigeniubidexiangmu with MIT License 5 votes vote down vote up
public HttpResponse getResponse(String url) throws ClientProtocolException, IOException {
	IdleConnectionMonitor();
	HttpRequestBase method = this.httpGetMethod(url);

	method.setConfig(requestConfig);
	HttpResponse response = client.execute(method);
	return response;
}
 
Example 16
Source File: NetServiceImpl.java    From onboard with Apache License 2.0 5 votes vote down vote up
private String excuteForString(HttpRequestBase requestBase) throws RuntimeException, InternalException {
    String authValue = getAuthorizationValue();
    if (authValue != null) {
        requestBase.addHeader("Authorization", authValue);
    }
    requestBase.setConfig(requestConfig);
    CloseableHttpClient httpClient = HttpClients.createDefault();
    CloseableHttpResponse response = sendRequest(httpClient, requestBase);

    return processResponseToString(httpClient, response);
}
 
Example 17
Source File: HttpClientHelper.java    From WeEvent with Apache License 2.0 5 votes vote down vote up
public <T> BaseResponse<T> invokeCGI(HttpRequestBase request, TypeReference<BaseResponse<T>> typeReference) throws BrokerException {
    long requestStartTime = System.currentTimeMillis();
    RequestConfig requestConfig = RequestConfig.custom()
            .setConnectTimeout(this.timeout)
            .setSocketTimeout(this.timeout)
            .build();
    request.setConfig(requestConfig);
    try (CloseableHttpResponse httpResponse = this.httpClient.execute(request)) {
        log.info("invokeCGI {} in {} millisecond, response:{}", request.getURI(),
                System.currentTimeMillis() - requestStartTime, httpResponse.getStatusLine().toString());
        if (HttpStatus.SC_OK != httpResponse.getStatusLine().getStatusCode()) {
            log.error("invokeCGI failed, request url:{}, msg:{}", request.getURI(), httpResponse.getStatusLine().toString());
            throw new BrokerException(ErrorCode.HTTP_RESPONSE_FAILED);
        }
        if (null == httpResponse.getEntity()) {
            log.error("invokeCGI failed, httpResponse.getEntity is null, request url:{}", request.getURI());
            throw new BrokerException(ErrorCode.HTTP_RESPONSE_ENTITY_EMPTY);
        }

        byte[] responseResult = EntityUtils.toByteArray(httpResponse.getEntity());
        BaseResponse<T> baseResponse = JsonHelper.json2Object(responseResult, typeReference);

        if (ErrorCode.SUCCESS.getCode() != baseResponse.getCode()) {
            log.error("invokeCGI failed, request url:{}, msg:{}", request.getURI(), baseResponse.getMessage());
            throw new BrokerException(baseResponse.getCode(), baseResponse.getMessage());
        }

        return baseResponse;
    } catch (IOException e) {
        log.error("invokeCGI error, request url:{}", request.getURI(), e);
        throw new BrokerException(ErrorCode.HTTP_REQUEST_EXECUTE_ERROR);
    }
}
 
Example 18
Source File: NetworkUtil.java    From openemm with GNU Affero General Public License v3.0 5 votes vote down vote up
public static void setHttpClientProxyFromSystem(HttpRequestBase request, String url) {
	String proxyHost = System.getProperty("http.proxyHost");
	if (StringUtils.isNotBlank(proxyHost)) {
		String proxyPort = System.getProperty("http.proxyPort");
		String nonProxyHosts = System.getProperty("http.nonProxyHosts");
		
		if (StringUtils.isBlank(nonProxyHosts)) {
			if (StringUtils.isNotBlank(proxyHost)) {
				if (StringUtils.isNotBlank(proxyPort) && AgnUtils.isNumber(proxyPort)) {
					request.setConfig(RequestConfig.custom().setProxy(new HttpHost(proxyHost, Integer.parseInt(proxyPort), "http")).build());
				} else {
					request.setConfig(RequestConfig.custom().setProxy(new HttpHost(proxyHost, 8080, "http")).build());
				}
			}
		} else {
			boolean ignoreProxy = false;
			String urlDomain = getDomainFromUrl(url);
			for (String nonProxyHost : nonProxyHosts.split("\\|")) {
				nonProxyHost = nonProxyHost.trim();
				if (urlDomain == null || urlDomain.equalsIgnoreCase(url)) {
					ignoreProxy = true;
					break;
				}
			}
			if (!ignoreProxy) {
				if (StringUtils.isNotBlank(proxyHost)) {
					if (StringUtils.isNotBlank(proxyPort) && AgnUtils.isNumber(proxyPort)) {
						request.setConfig(RequestConfig.custom().setProxy(new HttpHost(proxyHost, Integer.parseInt(proxyPort), "http")).build());
					} else {
						request.setConfig(RequestConfig.custom().setProxy(new HttpHost(proxyHost, 8080, "http")).build());
					}
				}
			}
		}
	}
}
 
Example 19
Source File: HttpClientUtil.java    From httpclientutil with Apache License 2.0 4 votes vote down vote up
/**
 * 请求资源或服务
 * 
 * @param config		请求参数配置
 * @return				返回HttpResponse对象
 * @throws HttpProcessException	http处理异常 
 */
private static HttpResponse execute(HttpConfig config) throws HttpProcessException {
	create(config);//获取链接
	HttpResponse resp = null;

	try {
		//创建请求对象
		HttpRequestBase request = getRequest(config.url(), config.method());
		
		//设置超时
		request.setConfig(config.requestConfig());
		
		//设置header信息
		request.setHeaders(config.headers());
		
		//判断是否支持设置entity(仅HttpPost、HttpPut、HttpPatch支持)
		if(HttpEntityEnclosingRequestBase.class.isAssignableFrom(request.getClass())){
			List<NameValuePair> nvps = new ArrayList<NameValuePair>();
			
			if(request.getClass()==HttpGet.class) {
				//检测url中是否存在参数
				//注:只有get请求,才自动截取url中的参数,post等其他方式,不再截取
				config.url(Utils.checkHasParas(config.url(), nvps, config.inenc()));
			}
			
			//装填参数
			HttpEntity entity = Utils.map2HttpEntity(nvps, config.map(), config.inenc());
			
			//设置参数到请求对象中
			((HttpEntityEnclosingRequestBase)request).setEntity(entity);
			
			Utils.info("请求地址:"+config.url());
			if(nvps.size()>0){
				Utils.info("请求参数:"+nvps.toString());
			}
			if(config.json()!=null){
				Utils.info("请求参数:"+config.json());
			}
		}else{
			int idx = config.url().indexOf("?");
			Utils.info("请求地址:"+config.url().substring(0, (idx>0 ? idx : config.url().length())));
			if(idx>0){
				Utils.info("请求参数:"+config.url().substring(idx+1));
			}
		}
		//执行请求操作,并拿到结果(同步阻塞)
		resp = (config.context()==null)?config.client().execute(request) : config.client().execute(request, config.context()) ;

		if(config.isReturnRespHeaders()){
			//获取所有response的header信息
			config.headers(resp.getAllHeaders());
		}
		
		//获取结果实体
		return resp;
		
	} catch (IOException e) {
		throw new HttpProcessException(e);
	}
}
 
Example 20
Source File: HttpProtocolTemplate.java    From dtsopensource with Apache License 2.0 4 votes vote down vote up
private void initRequestConfig(HttpRequestBase httpRequestBase) {
    // 配置请求的超时设置
    RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(timeOut)
            .setConnectTimeout(timeOut).setSocketTimeout(timeOut).build();
    httpRequestBase.setConfig(requestConfig);
}