Java Code Examples for org.apache.http.client.methods.CloseableHttpResponse#getAllHeaders()

The following examples show how to use org.apache.http.client.methods.CloseableHttpResponse#getAllHeaders() . 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: HttpClientBasic.java    From JavaTutorial with Apache License 2.0 6 votes vote down vote up
private void processResponse(CloseableHttpResponse response) 
            throws UnsupportedOperationException, IOException {
        try {
            // 获取响应头
            Header[] headers = response.getAllHeaders();
            for (Header header : headers) {
                _logger.info(header.getName() + ":" + header.getValue());
            }
            
            // 获取状态信息
            StatusLine sl =response.getStatusLine();
            _logger.info( String.format("ProtocolVersion:%s, StatusCode:%d, Desc:%s", 
                    sl.getProtocolVersion().toString(), sl.getStatusCode(), sl.getReasonPhrase()) );
            
            // 获取响应内容
            HttpEntity entity = response.getEntity();
            _logger.info( String.format("ContentType:%s, Length:%d, Encoding:%s", 
                    null == entity.getContentType() ? "" : entity.getContentType().getValue(), 
                    entity.getContentLength(),
                    null == entity.getContentEncoding() ? "" : entity.getContentEncoding().getValue()) );
            _logger.info(EntityUtils.toString(entity, _charset));
//            _logger.info( IOUtils.toString(entity.getContent(), _charset) ); // 大部分情况下效果与上行语句等同,但实现上的编码处理不同
        } finally {
            response.close();
        }
    }
 
Example 2
Source File: TestCustomizedHttpResponseHeaders.java    From rest-utils with Apache License 2.0 6 votes vote down vote up
private static String getResponseHeader(CloseableHttpResponse response, String name) {
  String value = null;
  Header[] headers = response.getAllHeaders();
  if (headers != null && headers.length > 0) {
    Arrays.stream(headers)
            .forEach(header -> log.debug("header name: {}, header value: {}.", header.getName(), header.getValue()));
  }

  headers = response.getHeaders(name);
  if (headers != null && headers.length > 0) {
    value = headers[0].getValue();
  }

  return value;
}
 
Example 3
Source File: HttpRequestException.java    From caravan with Apache License 2.0 6 votes vote down vote up
public HttpRequestException(CloseableHttpResponse response) {
    super(toErrorMessage(response));

    StatusLine statusLine = response.getStatusLine();
    if (statusLine == null)
        return;

    _statusCode = statusLine.getStatusCode();
    _reasonPhrase = statusLine.getReasonPhrase();
    _protocolVersion = statusLine.getProtocolVersion();
    _responseHeaders = response.getAllHeaders();

    HttpEntity entity = response.getEntity();
    if (entity == null)
        return;

    try (InputStream is = entity.getContent();) {
        _responseBody = EntityUtils.toString(entity);
    } catch (Throwable ex) {

    }
}
 
Example 4
Source File: HttpUtil.java    From anyline with Apache License 2.0 5 votes vote down vote up
private static HttpResult parseResult(HttpResult result, CloseableHttpResponse response, String encode) {
	if (null == result) {
		result = new HttpResult();
	} 
	try {
		if(null != response){ 
			Map<String, String> headers = new HashMap<String, String>(); 
			Header[] all = response.getAllHeaders(); 
			for (Header header : all) { 
				String key = header.getName(); 
				String value = header.getValue(); 
				headers.put(key, value); 
				if ("Set-Cookie".equalsIgnoreCase(key)) { 
					HttpCookie c = new HttpCookie(value);
					result.setCookie(c);
				} 
			} 
			int code = response.getStatusLine().getStatusCode();
			result.setHeaders(headers);
			result.setStatus(code);
			if(code ==200){ 
				HttpEntity entity = response.getEntity(); 
				if (null != entity) {
					result.setInputStream(entity.getContent());
					String text = EntityUtils.toString(entity, encode);
					result.setText(text);
				} 
			} 
		} 
	} catch (Exception e) { 
		e.printStackTrace(); 
	} 
	return result;
}
 
Example 5
Source File: HttpClientUtils.java    From train-ticket-reaper with MIT License 5 votes vote down vote up
public static List<String> cookiesByGet(String url, String userAgent, String referer, String cookie) throws IOException {
    HttpClientBuilder builder = HttpClients.custom();
    CloseableHttpClient client = builder.build();
    HttpGet httpGet = new HttpGet(url);
    httpGet.addHeader("Host", getHost(url));
    if (referer != null) {
        httpGet.addHeader("Referer", referer);
    }
    httpGet.addHeader("User-Agent", userAgent);
    if (cookie != null) {
        httpGet.addHeader("Cookie", cookie);
    }

    List<String> resultList = new LinkedList<>();
    CloseableHttpResponse response = client.execute(httpGet);
    for (Header header : response.getAllHeaders()) {
        if ("Set-Cookie".equals(header.getName())) {
            HeaderElement[] elements = header.getElements();
            resultList.add(elements[0].toString().split(";")[0]);
        }
    }
    if (resultList != null && resultList.size() > 0) {
        return resultList;
    } else {
        return null;
    }
}
 
Example 6
Source File: GenericHandler.java    From restfiddle with Apache License 2.0 5 votes vote down vote up
private RfResponseDTO buildRfResponse(CloseableHttpResponse httpResponse) throws IOException {
RfResponseDTO responseDTO = new RfResponseDTO();
String responseBody = "";
List<RfHeaderDTO> headers = new ArrayList<RfHeaderDTO>();
try {
    logger.info("response status : " + httpResponse.getStatusLine());
    responseDTO.setStatus(httpResponse.getStatusLine().getStatusCode() + " " + httpResponse.getStatusLine().getReasonPhrase());
    HttpEntity responseEntity = httpResponse.getEntity();
    Header[] responseHeaders = httpResponse.getAllHeaders();

    RfHeaderDTO headerDTO = null;
    for (Header responseHeader : responseHeaders) {
	// logger.info("response header - name : " + responseHeader.getName() + " value : " + responseHeader.getValue());
	headerDTO = new RfHeaderDTO();
	headerDTO.setHeaderName(responseHeader.getName());
	headerDTO.setHeaderValue(responseHeader.getValue());
	headers.add(headerDTO);
    }
    Header contentType = responseEntity.getContentType();
    logger.info("response contentType : " + contentType);

    // logger.info("content : " + EntityUtils.toString(responseEntity));
    responseBody = EntityUtils.toString(responseEntity);
    EntityUtils.consume(responseEntity);
} finally {
    httpResponse.close();
}
responseDTO.setBody(responseBody);
responseDTO.setHeaders(headers);
return responseDTO;
   }
 
Example 7
Source File: RawHttpComponentsClient.java    From rawhttp with Apache License 2.0 5 votes vote down vote up
private RawHttpHeaders readHeaders(CloseableHttpResponse response) {
    Header[] allHeaders = response.getAllHeaders();
    RawHttpHeaders.Builder headers = RawHttpHeaders.newBuilder();
    for (Header header : allHeaders) {
        String meta = header.getElements().length > 0 ?
                ";" + Arrays.stream(header.getElements())
                        .flatMap(it -> Arrays.stream(it.getParameters()).map(v -> v.getName() + "=" + v.getValue()))
                        .collect(joining(";")) :
                "";
        headers.with(header.getName(), header.getValue() + meta);
    }
    return headers.build();
}
 
Example 8
Source File: HttpUtils.java    From bce-sdk-java with Apache License 2.0 5 votes vote down vote up
public static void printResponse(CloseableHttpResponse response) {
    if (!HTTP_VERBOSE) {
        return;
    }
    System.out.println("\n<------------- ");
    StatusLine status = response.getStatusLine();
    System.out.println(status.getStatusCode() + " - "
            + status.getReasonPhrase());
    Header[] heads = response.getAllHeaders();
    for (Header h : heads) {
        System.out.println(h.getName() + " : " + h.getValue());
    }
}
 
Example 9
Source File: BasicHttpClient.java    From zerocode with Apache License 2.0 5 votes vote down vote up
/**
 * Once the client executes the http call, then it receives the http response. This method takes care of handling
 * that. In case you need to handle it differently you can override this method.
 *
 * @param httpResponse  : Received Apache http response from the server
 *
 * @return  : Effective response with handled http session.
 * @throws IOException
 */
public Response handleResponse(CloseableHttpResponse httpResponse) throws IOException {
    Response serverResponse = createCharsetResponse(httpResponse);

    Header[] allHeaders = httpResponse.getAllHeaders();
    Response.ResponseBuilder responseBuilder = Response.fromResponse(serverResponse);
    for (Header thisHeader : allHeaders) {
        String headerKey = thisHeader.getName();
        responseBuilder = responseBuilder.header(headerKey, thisHeader.getValue());

        handleHttpSession(serverResponse, headerKey);
    }

    return responseBuilder.build();
}
 
Example 10
Source File: ClientImpl.java    From datamill with ISC License 5 votes vote down vote up
private Map<String, String> populateResponseHeaders(CloseableHttpResponse httpResponse) {
    Map<String, String> combinedHeaders = new HashMap<>();

    for (Header header : httpResponse.getAllHeaders()) {
        combinedHeaders.put(header.getName(), header.getValue());
    }

    return combinedHeaders;
}
 
Example 11
Source File: PluginHelper.java    From zrlog with Apache License 2.0 5 votes vote down vote up
public static CloseResponseHandle getContext(String uri, String method, HttpServletRequest request, boolean disableRedirect, AdminTokenVO adminTokenVO) throws IOException, InstantiationException {
    String pluginServerHttp = Constants.pluginServer;
    CloseableHttpResponse httpResponse;
    CloseResponseHandle handle = new CloseResponseHandle();
    HttpUtil httpUtil = disableRedirect ? HttpUtil.getDisableRedirectInstance() : HttpUtil.getInstance();
    //GET请求不关心request.getInputStream() 的数据
    if (method.equals(request.getMethod()) && "GET".equalsIgnoreCase(method)) {
        httpResponse = httpUtil.sendGetRequest(pluginServerHttp + uri, request.getParameterMap(), handle, PluginHelper.genHeaderMapByRequest(request, adminTokenVO)).getT();
    } else {
        //如果是表单数据提交不关心请求头,反之将所有请求头都发到插件服务
        if ("application/x-www-form-urlencoded".equals(request.getContentType())) {
            httpResponse = httpUtil.sendPostRequest(pluginServerHttp + uri, request.getParameterMap(), handle, PluginHelper.genHeaderMapByRequest(request, adminTokenVO)).getT();
        } else {
            httpResponse = httpUtil.sendPostRequest(pluginServerHttp + uri + "?" + request.getQueryString(), IOUtil.getByteByInputStream(request.getInputStream()), handle, PluginHelper.genHeaderMapByRequest(request, adminTokenVO)).getT();
        }
    }
    //添加插件服务的HTTP响应头到调用者响应头里面
    if (httpResponse != null) {
        Map<String, String> headerMap = new HashMap<>();
        Header[] headers = httpResponse.getAllHeaders();
        for (Header header : headers) {
            headerMap.put(header.getName(), header.getValue());
        }
        if (BlogBuildInfoUtil.isDev()) {
            LOGGER.info("{} --------------------------------- response",uri);
        }
        for (Map.Entry<String, String> t : headerMap.entrySet()) {
            if (BlogBuildInfoUtil.isDev()) {
                LOGGER.info("{} value-> {}" ,t.getKey(), t.getValue());
            }
        }
    }
    return handle;
}
 
Example 12
Source File: ArchiveTask.java    From archivo with GNU General Public License v3.0 5 votes vote down vote up
private long getEstimatedLengthFromHeaders(CloseableHttpResponse response) {
    long length = -1;
    for (Header header : response.getAllHeaders()) {
        if (header.getName().equalsIgnoreCase("TiVo-Estimated-Length")) {
            try {
                length = Long.parseLong(header.getValue());
            } catch (NumberFormatException e) {
                logger.error("Error parsing estimated length ({}): ", header.getValue(), e);
            }
        }
    }
    return length;
}
 
Example 13
Source File: HTTP.java    From pentaho-kettle with Apache License 2.0 4 votes vote down vote up
protected Header[] searchForHeaders( CloseableHttpResponse response ) {
  return response.getAllHeaders();
}
 
Example 14
Source File: OAuthClient.java    From keycloak with Apache License 2.0 4 votes vote down vote up
public AccessTokenResponse(CloseableHttpResponse response) throws Exception {
    try {
        statusCode = response.getStatusLine().getStatusCode();

        headers = new HashMap<>();

        for (Header h : response.getAllHeaders()) {
            headers.put(h.getName(), h.getValue());
        }

        Header[] contentTypeHeaders = response.getHeaders("Content-Type");
        String contentType = (contentTypeHeaders != null && contentTypeHeaders.length > 0) ? contentTypeHeaders[0].getValue() : null;
        if (!"application/json".equals(contentType)) {
            Assert.fail("Invalid content type. Status: " + statusCode + ", contentType: " + contentType);
        }

        String s = IOUtils.toString(response.getEntity().getContent(), "UTF-8");
        Map responseJson = JsonSerialization.readValue(s, Map.class);

        if (statusCode == 200) {
            idToken = (String) responseJson.get("id_token");
            accessToken = (String) responseJson.get("access_token");
            issuedTokenType = (String) responseJson.get("issued_token_type");
            tokenType = (String) responseJson.get("token_type");
            expiresIn = (Integer) responseJson.get("expires_in");
            refreshExpiresIn = (Integer) responseJson.get("refresh_expires_in");
            sessionState = (String) responseJson.get("session_state");

            // OIDC Financial API Read Only Profile : scope MUST be returned in the response from Token Endpoint
            if (responseJson.containsKey(OAuth2Constants.SCOPE)) {
                scope = (String) responseJson.get(OAuth2Constants.SCOPE);
            }

            if (responseJson.containsKey(OAuth2Constants.REFRESH_TOKEN)) {
                refreshToken = (String) responseJson.get(OAuth2Constants.REFRESH_TOKEN);
            }
        } else {
            error = (String) responseJson.get(OAuth2Constants.ERROR);
            errorDescription = responseJson.containsKey(OAuth2Constants.ERROR_DESCRIPTION) ? (String) responseJson.get(OAuth2Constants.ERROR_DESCRIPTION) : null;
        }
    } finally {
        response.close();
    }
}
 
Example 15
Source File: App.java    From iot-device-bosch-indego-controller with Apache License 2.0 4 votes vote down vote up
public static void main (String[] args) throws ClientProtocolException, IOException,
        InterruptedException
{
    CloseableHttpClient httpClient = HttpClients.createDefault();

    HttpPost httpPost = new HttpPost(BASE_URL_PUSHWOOSH + "registerDevice");
    String jsonPost = ""//
            + "{" //
            + "  \"request\":{" //
            + "     \"application\":\"8FF60-0666B\"," //
            + "     \"push_token\":\"124692134091\"," //
            + "     \"hwid\":\"00-0C-29-E8-B1-8D\"," //
            + "     \"timezone\":3600," //
            + "     \"device_type\":3" //
            + "  }" //
            + "}";
    httpPost.setEntity(new StringEntity(jsonPost, ContentType.APPLICATION_JSON));
    CloseableHttpResponse response = httpClient.execute(httpPost);

    System.out.println(response.getStatusLine());
    Header[] headers = response.getAllHeaders();
    for (int i = 0; i < headers.length; i++) {
        System.out.println(headers[i].getName() + ": " + headers[i].getValue());
    }
    HttpEntity entity = response.getEntity();
    String contents = EntityUtils.toString(entity);
    System.out.println(contents);

    Thread.sleep(5000);

    HttpPost httpGet = new HttpPost(BASE_URL_PUSHWOOSH + "checkMessage");
    String jsonGet = ""//
            + "{" //
            + "  \"request\":{" //
            + "     \"application\":\"8FF60-0666B\"," //
            + "     \"hwid\":\"00-0C-29-E8-B1-8D\"" //
            + "  }" //
            + "}";
    httpGet.setEntity(new StringEntity(jsonGet, ContentType.APPLICATION_JSON));
    httpClient.execute(httpGet);

    response.close();
}
 
Example 16
Source File: HttpComponentsConnector.java    From cyberduck with GNU General Public License v3.0 4 votes vote down vote up
@Override
public ClientResponse apply(final ClientRequest clientRequest) throws ProcessingException {
    final HttpUriRequest request = this.toUriHttpRequest(clientRequest);
    final Map<String, String> clientHeadersSnapshot = writeOutBoundHeaders(clientRequest.getHeaders(), request);

    try {
        final CloseableHttpResponse response;
        response = client.execute(new HttpHost(request.getURI().getHost(), request.getURI().getPort(), request.getURI().getScheme()), request, new BasicHttpContext(context));
        HeaderUtils.checkHeaderChanges(clientHeadersSnapshot, clientRequest.getHeaders(), this.getClass().getName());

        final Response.StatusType status = response.getStatusLine().getReasonPhrase() == null
                ? Statuses.from(response.getStatusLine().getStatusCode())
                : Statuses.from(response.getStatusLine().getStatusCode(), response.getStatusLine().getReasonPhrase());

        final ClientResponse responseContext = new ClientResponse(status, clientRequest);
        final List<URI> redirectLocations = context.getRedirectLocations();
        if(redirectLocations != null && !redirectLocations.isEmpty()) {
            responseContext.setResolvedRequestUri(redirectLocations.get(redirectLocations.size() - 1));
        }

        final Header[] respHeaders = response.getAllHeaders();
        final MultivaluedMap<String, String> headers = responseContext.getHeaders();
        for(final Header header : respHeaders) {
            final String headerName = header.getName();
            List<String> list = headers.get(headerName);
            if(list == null) {
                list = new ArrayList<>();
            }
            list.add(header.getValue());
            headers.put(headerName, list);
        }

        final HttpEntity entity = response.getEntity();

        if(entity != null) {
            if(headers.get(HttpHeaders.CONTENT_LENGTH) == null) {
                headers.add(HttpHeaders.CONTENT_LENGTH, String.valueOf(entity.getContentLength()));
            }

            final Header contentEncoding = entity.getContentEncoding();
            if(headers.get(HttpHeaders.CONTENT_ENCODING) == null && contentEncoding != null) {
                headers.add(HttpHeaders.CONTENT_ENCODING, contentEncoding.getValue());
            }
        }
        responseContext.setEntityStream(this.toInputStream(response));
        return responseContext;
    }
    catch(final Exception e) {
        throw new ProcessingException(e);
    }
}
 
Example 17
Source File: HttpComponentsConnector.java    From cyberduck with GNU General Public License v3.0 4 votes vote down vote up
@Override
public ClientResponse apply(final ClientRequest clientRequest) throws ProcessingException {
    final HttpUriRequest request = this.toUriHttpRequest(clientRequest);
    final Map<String, String> clientHeadersSnapshot = writeOutBoundHeaders(clientRequest.getHeaders(), request);

    try {
        final CloseableHttpResponse response;
        response = client.execute(new HttpHost(request.getURI().getHost(), request.getURI().getPort(), request.getURI().getScheme()), request, new BasicHttpContext(context));
        HeaderUtils.checkHeaderChanges(clientHeadersSnapshot, clientRequest.getHeaders(), this.getClass().getName());

        final Response.StatusType status = response.getStatusLine().getReasonPhrase() == null
            ? Statuses.from(response.getStatusLine().getStatusCode())
            : Statuses.from(response.getStatusLine().getStatusCode(), response.getStatusLine().getReasonPhrase());

        final ClientResponse responseContext = new ClientResponse(status, clientRequest);
        final List<URI> redirectLocations = context.getRedirectLocations();
        if(redirectLocations != null && !redirectLocations.isEmpty()) {
            responseContext.setResolvedRequestUri(redirectLocations.get(redirectLocations.size() - 1));
        }

        final Header[] respHeaders = response.getAllHeaders();
        final MultivaluedMap<String, String> headers = responseContext.getHeaders();
        for(final Header header : respHeaders) {
            final String headerName = header.getName();
            List<String> list = headers.get(headerName);
            if(list == null) {
                list = new ArrayList<>();
            }
            list.add(header.getValue());
            headers.put(headerName, list);
        }

        final HttpEntity entity = response.getEntity();

        if(entity != null) {
            if(headers.get(HttpHeaders.CONTENT_LENGTH) == null) {
                headers.add(HttpHeaders.CONTENT_LENGTH, String.valueOf(entity.getContentLength()));
            }

            final Header contentEncoding = entity.getContentEncoding();
            if(headers.get(HttpHeaders.CONTENT_ENCODING) == null && contentEncoding != null) {
                headers.add(HttpHeaders.CONTENT_ENCODING, contentEncoding.getValue());
            }
        }
        responseContext.setEntityStream(this.toInputStream(response));
        return responseContext;
    }
    catch(final Exception e) {
        throw new ProcessingException(e);
    }
}
 
Example 18
Source File: ApacheHttpClient.java    From karate with MIT License 4 votes vote down vote up
@Override
protected HttpResponse makeHttpRequest(HttpEntity entity, ScenarioContext context) {
    if (entity != null) {
        requestBuilder.setEntity(entity);
        requestBuilder.setHeader(entity.getContentType());
    }
    HttpUriRequest httpRequest = requestBuilder.build();
    CloseableHttpClient client = clientBuilder.build();
    BasicHttpContext httpContext = new BasicHttpContext();
    httpContext.setAttribute(URI_CONTEXT_KEY, getRequestUri());
    CloseableHttpResponse httpResponse;
    byte[] bytes;
    try {
        httpResponse = client.execute(httpRequest, httpContext);
        HttpEntity responseEntity = httpResponse.getEntity();
        if (responseEntity == null || responseEntity.getContent() == null) {
            bytes = new byte[0];
        } else {
            InputStream is = responseEntity.getContent();
            bytes = FileUtils.toBytes(is);
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    HttpRequest actualRequest = context.getPrevRequest();
    HttpResponse response = new HttpResponse(actualRequest.getStartTime(), actualRequest.getEndTime());
    response.setUri(getRequestUri());
    response.setBody(bytes);
    response.setStatus(httpResponse.getStatusLine().getStatusCode());
    for (Cookie c : cookieStore.getCookies()) {
        com.intuit.karate.http.Cookie cookie = new com.intuit.karate.http.Cookie(c.getName(), c.getValue());
        cookie.put(DOMAIN, c.getDomain());
        cookie.put(PATH, c.getPath());
        if (c.getExpiryDate() != null) {
            cookie.put(EXPIRES, c.getExpiryDate().getTime() + "");
        }
        cookie.put(PERSISTENT, c.isPersistent() + "");
        cookie.put(SECURE, c.isSecure() + "");
        response.addCookie(cookie);
    }
    cookieStore.clear(); // we rely on the StepDefs for cookie 'persistence'
    for (Header header : httpResponse.getAllHeaders()) {
        response.addHeader(header.getName(), header.getValue());
    }
    return response;
}
 
Example 19
Source File: RESTClient.java    From rest-client with Apache License 2.0 4 votes vote down vote up
/**
* 
* @Title: exec 
* @Description: Execute HTTP request 
* @param @param hreq
* @param @param ureq
* @param @return 
* @return HttpRsp
* @throws
 */
private HttpRsp exec(HttpRequestBase req)
{
    CloseableHttpResponse hr = null;
    HttpRsp rsp = new HttpRsp();

    try
    {
        /* Send HTTP request */
        hr = hc.execute(req);
        HttpEntity he = hr.getEntity();
        if (null != he)
        {
            /* Receive HTTP response */
            String body = EntityUtils.toString(he, Charsets.UTF_8.getCname());
            if (null == body)
            {
                body = StringUtils.EMPTY;
            }
            rsp.setBody(body);
        }
        else 
        {
            log.warn("HTTP response is null.");
        }

        hr.setReasonPhrase("");
        rsp.setStatus(hr.getStatusLine().toString());
        rsp.setStatusCode(hr.getStatusLine().getStatusCode());
        rsp.setHeaders(new HashMap<String, String>());

        for (Header hdr : hr.getAllHeaders())
        {
            rsp.getHeaders().put(hdr.getName(), hdr.getValue());
        }
    }
    catch(Throwable e)
    {
        log.error("Http request failed.", e);
    } 
    finally
    {
        HttpClientUtils.closeQuietly(hr);
    }

    return rsp;
}
 
Example 20
Source File: Http.java    From hop with Apache License 2.0 4 votes vote down vote up
protected Header[] searchForHeaders( CloseableHttpResponse response ) {
  return response.getAllHeaders();
}