Java Code Examples for org.apache.http.Header#getValue()

The following examples show how to use org.apache.http.Header#getValue() . 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: ConanProxySearchIT.java    From nexus-repository-conan with Eclipse Public License 1.0 6 votes vote down vote up
@Test
public void patternSearch() throws Exception {
  HttpResponse response = proxyClient.getHttpResponse(PATH_PATTERN_SEARCH);
  assertThat(status(response), is(HttpStatus.OK));

  HttpEntity entity = response.getEntity();
  String actualJson = EntityUtils.toString(entity);
  assertThat(actualJson, is(MOCK_PATTERN_SEARCH_REMOTE_RESPONSE));

  Header contentType = response.getEntity().getContentType();
  String mimeType = contentType.getValue();
  assertThat(mimeType, is(ContentTypes.APPLICATION_JSON));

  Asset conanManifestAsset = findAsset(proxyRepo, PATH_MANIFEST);
  assertThat(conanManifestAsset, nullValue());

  Asset downloadUrlsAsset = findAsset(proxyRepo, PATH_DOWNLOAD_URLS);
  assertThat(downloadUrlsAsset, nullValue());

  Asset digestAsset = findAsset(proxyRepo, PATH_DIGEST);
  assertThat(digestAsset, nullValue());
}
 
Example 2
Source File: HttpResponseConsumer.java    From cs-actions with Apache License 2.0 6 votes vote down vote up
public void consume(Map<String, String> result) throws IOException {
    if (httpResponse.getEntity() != null) {
        if (responseCharacterSet == null || responseCharacterSet.isEmpty()) {
            Header contentType = httpResponse.getEntity().getContentType();
            if (contentType != null) {
                String value = contentType.getValue();
                NameValuePair[] nameValuePairs = BasicHeaderValueParser.parseParameters(value, BasicHeaderValueParser.INSTANCE);
                for (NameValuePair nameValuePair : nameValuePairs) {
                    if (nameValuePair.getName().equalsIgnoreCase("charset")) {
                        responseCharacterSet = nameValuePair.getValue();
                        break;
                    }
                }
            }
            if (responseCharacterSet == null || responseCharacterSet.isEmpty()) {
                responseCharacterSet = Consts.ISO_8859_1.name();
            }
        }
        consumeResponseContent(result);
    }
}
 
Example 3
Source File: HttpEntityPayload.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Nullable
@Override
public String getContentType() {
  Header header = entity.getContentType();
  if (header != null) {
    return header.getValue();
  }
  return null;
}
 
Example 4
Source File: AwsSigner4Request.java    From jkube with Eclipse Public License 2.0 5 votes vote down vote up
private static String getSigningDateTime(HttpRequest request, Date signingTime) {
    Header dateHeader = request.getFirstHeader("X-Amz-Date");
    if (dateHeader != null) {
        return dateHeader.getValue();
    }
    final SimpleDateFormat timeFormat= new SimpleDateFormat("yyyyMMdd'T'HHmmss'Z'");
    timeFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
    return timeFormat.format(signingTime);
}
 
Example 5
Source File: HttpResponseUtils.java    From esigate with Apache License 2.0 5 votes vote down vote up
/**
 * Get the value of the first header matching "headerName".
 * 
 * @param headerName
 * @param httpResponse
 * @return value of the first header or null if it doesn't exist.
 */
public static String getFirstHeader(String headerName, HttpResponse httpResponse) {
    Header header = httpResponse.getFirstHeader(headerName);
    if (header != null) {
        return header.getValue();
    }
    return null;
}
 
Example 6
Source File: CasAuthenticationHandler.java    From esigate with Apache License 2.0 5 votes vote down vote up
private boolean isRedirectToCasServer(HttpResponse httpResponse) {
    Header locationHeader = httpResponse.getFirstHeader("Location");
    if (locationHeader != null) {
        String locationHeaderValue = locationHeader.getValue();
        if (locationHeaderValue != null && locationHeaderValue.contains(loginUrl)) {
            return true;
        }
    }
    return false;
}
 
Example 7
Source File: RetryHeaderUtils.java    From FcmJava with MIT License 5 votes vote down vote up
private static boolean internalTryDetermineRetryDelay(HttpResponse httpResponse, OutParameter<Duration> result) {

        // Try to get the Retry-After Header send by FCM:
        Header retryAfterHeader = httpResponse.getFirstHeader("Retry-After");

        // Early exit, if we do not have a Retry Header:
        if (retryAfterHeader == null) {
            return false;
        }

        // Try to get the Value:
        String retryDelayAsString = retryAfterHeader.getValue();

        // Early exit, if the Retry Header has no Value:
        if(StringUtils.isNullOrWhiteSpace(retryDelayAsString)) {
            return false;
        }

        // First check if we have a Number Retry Delay as Seconds:
        if(tryGetFromLong(retryDelayAsString, result)) {
            return true;
        }

        // Then check if we have a RFC1123-compliant date:
        if(tryGetFromDate(retryDelayAsString, result)) {
            return true;
        }

        return false;
    }
 
Example 8
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 9
Source File: YadisResolver.java    From openid4java with Apache License 2.0 5 votes vote down vote up
/**
 * Tries to retrieve the XRDS document via a GET call on XRDS location
 * provided in the result parameter.
 *
 * @param result        The YadisResult object containing a valid XRDS location.
 *                      It will be further populated with the Yadis discovery results.
 * @param cache        The HttpClient object to use for placing the call
 * @param maxRedirects
 */
private void retrieveXrdsDocument(YadisResult result, int maxRedirects, Set serviceTypes)
    throws DiscoveryException {

    _httpFetcher.getRequestOptions().setMaxRedirects(maxRedirects);

    try {
        HttpResponse resp = _httpFetcher.get(result.getXrdsLocation().toString());

        if (resp == null || HttpStatus.SC_OK != resp.getStatusCode())
            throw new YadisException("GET failed on " + result.getXrdsLocation(),
                    OpenIDException.YADIS_GET_ERROR);

        // update xrds location, in case redirects were followed
        result.setXrdsLocation(resp.getFinalUri(), OpenIDException.YADIS_GET_INVALID_RESPONSE);

        Header contentType = resp.getResponseHeader("content-type");
        if ( contentType != null && contentType.getValue() != null)
            result.setContentType(contentType.getValue());

        if (resp.isBodySizeExceeded())
            throw new YadisException(
                "More than " + _httpFetcher.getRequestOptions().getMaxBodySize() +
                " bytes in HTTP response body from " + result.getXrdsLocation(),
                OpenIDException.YADIS_XRDS_SIZE_EXCEEDED);
        result.setEndpoints(XRDS_PARSER.parseXrds(resp.getBody(), serviceTypes));

    } catch (IOException e) {
        throw new YadisException("Fatal transport error: " + e.getMessage(),
                OpenIDException.YADIS_GET_TRANSPORT_ERROR, e);
    }
}
 
Example 10
Source File: Response.java    From hbase with Apache License 2.0 5 votes vote down vote up
public String getHeader(String key) {
  for (Header header : headers) {
    if (header.getName().equalsIgnoreCase(key)) {
      return header.getValue();
    }
  }
  return null;
}
 
Example 11
Source File: CreateScanner.java    From knox with Apache License 2.0 5 votes vote down vote up
public String getScannerId() {
  Header locationHeader = response().getFirstHeader( "Location" );
  if( locationHeader != null && locationHeader.getValue() != null && !locationHeader.getValue().isEmpty() ) {
    String location = locationHeader.getValue();
    int position = location.lastIndexOf( '/' );
    if( position != -1 ) {
      return location.substring( position + 1 );
    }
  }
  return null;
}
 
Example 12
Source File: HttpRequest.java    From opentest with MIT License 4 votes vote down vote up
public String getFirstHeader(String headerName) {
    Header header = this.response.getFirstHeader(headerName);
    return header != null ? header.getValue() : null;
}
 
Example 13
Source File: UnionService.java    From seezoon-framework-all with Apache License 2.0 4 votes vote down vote up
@Test
public void payPage() throws ParseException, Exception {
	String mobile = "13249073372";
	String email= "[email protected]";
	String phoneVerifyCode="874501";
	CookieStore cookieStore = valueOperations.get(mobile);
	HttpClientContext httpClientContext = HttpClientContext.create();
	httpClientContext.setCookieStore(cookieStore);
	String url = UriComponentsBuilder.fromHttpUrl("https://upay.10010.com/npfweb/NpfWeb/buyCard/buyCardSubmit").build().toUriString();
	HttpPost request = new HttpPost(url);
	Map<String, String> params = new HashMap<String,String>();
	params.put("cardBean.cardValueCode", "04");
	params.put("offerPriceStrHidden", "100.00");
	params.put("offerRateStrHidden", "1");
	params.put("cardBean.cardValue", "100");
	params.put("cardBean.minCardNum", "1");
	params.put("cardBean.maxCardNum", "3");
	params.put("MaxThreshold01", "15");
	params.put("MinThreshold01", "1");
	params.put("MaxThreshold02", "10");
	params.put("MinThreshold02", "1");
	params.put("MaxThreshold03", "6");
	params.put("MinThreshold03", "1");
	params.put("MaxThreshold04", "3");
	params.put("MinThreshold04", "1");
	params.put("commonBean.channelType", "101");
	//params.put("secstate.state", IOUtils.toString(new FileReader("/Users/hdf/Desktop/1.txt")));
	params.put("secstate.state", "FYlSiTsg5fqfr+wYGrqIRsetX8HDhLNTieb9/vhIHd1T+Hn5TFUBZdV9xR8nsIPRJXIsCwNfl2X+\\nw0sbN+O733sOywtoDmSU3uaYdnBYqPe8IxAtxwFBfYu2KOg4tCVKpSHRz9YutD8oAE0p24CNzliO\\nGRr/Kmt8YTVIYBqI51b3JBw8HC/efyVNcKlk30Q8/vcCkeDvuOJW1HImZ4IfsHt6CGzaDnDIuKnb\\nlL5TTJSZy9UnwiNX7U+OHY5G/jMMpMsY4N1CLFvG2ltsTckeMcJHUvxgU5esWqpOh+TLcbgd9pZe\\nSNdfojJDJ4uusMt8s/tboc3mLUWwpXavlp/sCs8U2JIgbX3UBXlNEpuZTLe/nYAolG9JRue0EwPr\\n1S+wIUWghK+mqzfcQFMANVOkpKaEGXx2LUk4cdCqjYHN7Cm3O8QzK3LXfWyzcaAfNO/pd29SPBlz\\ndNrsX+uRbAuxANeiTWUEG3jWWj1OzTU4cCSyU0/wmaSnUKTxC0v2HbA9ZvX5cHxkYiXlGPuXYHpE\\na1DXlFsWcN0tcCxfoe5GieycKWCnTWlHX7Hbm+4ElHaOKR52m3FGnYdGSFPQ13Eq/jvWDhks8V5o\\nDr+VzoFEbZOJSlf4s7uiA4zvUuV7JN9xR8nwfR2ePD9r+kujnaAW3hS4b+fSKROHt020z4pq3mNH\\nyweCgZ78HjGeFVuB1sC9pMVo7J0v/GJwF10WPfT68NyS2jt2k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BQylu/OxIkXk7F+gG5BeWEUotYwUH4P0t9\\n5bdg4HUhHPG8Rg995kTlIrrMCQOHMgAbTNGp0aAAMkm9SgTAP7ekN2joOfFSEcn6adgvRgcZFril\\nOjXHMDHWcMpccv+SaVjwTfEf1cY6aE6LH8ty+NC2R97ExHn/UIucsBm1KemZ1zaWQy/LbRxDWtmu\\n15HZr9kJLCAEm2UhESAg+gzfCd5sPqtGk59E/7BXMyJ3SK9mChytiT8si5HMeDMzdsbqQhoqLJRB\\nGSRzdyEqR8mPiueUo7WQxK8x38+RPcfC4UPL4NA3CrYYSWLPPPKwjtRxWTEIKpNZxfS8OyFO5uvA\\ntznwNHFrIryz4RMaSbajBXdHu6sBynPBa1CjOxTg44x2YdaTJiIspnYZF3qkp3eewmp7z+UxZJwp\\n1Jjfn5GsuzIs3V/O4ktBFkZTYL17fU5o/GxTmm8uMbp6ByV71RgzvqLo2nvRah3jypNtjN+ZrrTL\\n9JfwSm9YD82ecsrgIuRBiuUDibk7thXTNISBcSxtLhuSdsfonEKVJNnKKNb5G9+b8+ZGEl/Zbbkm\\n6QstnWr9nQL4kb0VhZmZTJfzfx7x2DiV+/BqLDSReHo6^@^0.0.1");
	params.put("cardBean.buyCardAmount", "1");
	params.put("cardBean.buyCardEmail", email);
	params.put("cardBean.buyCardPhoneNo", mobile);
	params.put("phoneVerifyCode",phoneVerifyCode);
	params.put("invoiceBean.need_invoice", "	0");
	params.put("invoiceBean.invoice_type	", "");
	params.put("invoiceBean.is_mailing", "0");
	params.put("saveflag	", "false");
	params.put("commonBean.provinceCode", "");
	params.put("commonBean.cityCode", "");
	params.put("invoiceBean.invoice_list	", "");
	request.setEntity(getUrlEncodedFormEntity(params));
	request.setHeader("Referer", "https://upay.10010.com/npfweb/npfbuycardweb/buycard_recharge_fill.htm");
	request.setHeader("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.181 Safari/537.36");
	CloseableHttpResponse response = client.execute(request, httpClientContext);
	System.out.println("response:" + JSON.toJSONString(response));
	if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode()) {// 成功
		HttpEntity entity = response.getEntity();
		if (null != entity) {
			String result = EntityUtils.toString(entity, "UTF-8");
			EntityUtils.consume(entity);
			System.out.println("result" + result);
		} else {
			throw new ServiceException("请求无数据返回");
		}
	} else if (response.getStatusLine().getStatusCode() == 302) {
		Header header = response.getFirstHeader("location"); // 跳转的目标地址是在 HTTP-HEAD 中的
		String newuri = header.getValue(); // 这就是跳转后的地址,再向这个地址发出新申请,以便得到跳转后的信息是啥。
		System.out.println("redirect url:" + newuri);
		HttpGet redirectRequest = new HttpGet(newuri);
		CloseableHttpResponse response2 = client.execute(redirectRequest, httpClientContext);
		System.out.println("response2:" + JSON.toJSONString(response2));
	} else {
		throw new ServiceException("请求状态异常失败");
	}
}
 
Example 14
Source File: HeaderManager.java    From esigate with Apache License 2.0 4 votes vote down vote up
/**
 * Copies end-to-end headers from a response received from the server to the response to be sent to the client.
 * 
 * @param outgoingRequest
 *            the request sent
 * @param incomingRequest
 *            the original request received from the client
 * @param httpClientResponse
 *            the response received from the provider application
 * @return the response to be sent to the client
 */
public CloseableHttpResponse copyHeaders(OutgoingRequest outgoingRequest,
        HttpEntityEnclosingRequest incomingRequest, HttpResponse httpClientResponse) {
    HttpResponse result = new BasicHttpResponse(httpClientResponse.getStatusLine());
    result.setEntity(httpClientResponse.getEntity());
    String originalUri = incomingRequest.getRequestLine().getUri();
    String baseUrl = outgoingRequest.getBaseUrl().toString();
    String visibleBaseUrl = outgoingRequest.getOriginalRequest().getVisibleBaseUrl();
    for (Header header : httpClientResponse.getAllHeaders()) {
        String name = header.getName();
        String value = header.getValue();
        try {
            // Ignore Content-Encoding and Content-Type as these headers are
            // set in HttpEntity
            if (!HttpHeaders.CONTENT_ENCODING.equalsIgnoreCase(name)) {
                if (isForwardedResponseHeader(name)) {
                    // Some headers containing an URI have to be rewritten
                    if (HttpHeaders.LOCATION.equalsIgnoreCase(name)
                            || HttpHeaders.CONTENT_LOCATION.equalsIgnoreCase(name)) {
                        // Header contains only an url
                        value = urlRewriter.rewriteUrl(value, originalUri, baseUrl, visibleBaseUrl, true);
                        value = HttpResponseUtils.removeSessionId(value, httpClientResponse);
                        result.addHeader(name, value);
                    } else if ("Link".equalsIgnoreCase(name)) {
                        // Header has the following format
                        // Link: </feed>; rel="alternate"

                        if (value.startsWith("<") && value.contains(">")) {
                            String urlValue = value.substring(1, value.indexOf(">"));

                            String targetUrlValue =
                                    urlRewriter.rewriteUrl(urlValue, originalUri, baseUrl, visibleBaseUrl, true);
                            targetUrlValue = HttpResponseUtils.removeSessionId(targetUrlValue, httpClientResponse);

                            value = value.replace("<" + urlValue + ">", "<" + targetUrlValue + ">");
                        }

                        result.addHeader(name, value);

                    } else if ("Refresh".equalsIgnoreCase(name)) {
                        // Header has the following format
                        // Refresh: 5; url=http://www.example.com
                        int urlPosition = value.indexOf("url=");
                        if (urlPosition >= 0) {
                            value = urlRewriter.rewriteRefresh(value, originalUri, baseUrl, visibleBaseUrl);
                            value = HttpResponseUtils.removeSessionId(value, httpClientResponse);
                        }
                        result.addHeader(name, value);
                    } else if ("P3p".equalsIgnoreCase(name)) {
                        // Do not translate url yet.
                        // P3P is used with a default fixed url most of the
                        // time.
                        result.addHeader(name, value);
                    } else {
                        result.addHeader(header.getName(), header.getValue());
                    }
                }
            }
        } catch (Exception e1) {
            // It's important not to fail here.
            // An application can always send corrupted headers, and we
            // should not crash
            LOG.error("Error while copying headers", e1);
            result.addHeader("X-Esigate-Error", "Error processing header " + name + ": " + value);
        }
    }
    return BasicCloseableHttpResponse.adapt(result);
}
 
Example 15
Source File: Dictionary.java    From ongdb-lab-apoc with Apache License 2.0 4 votes vote down vote up
/**
 * 从远程服务器上下载自定义词条
 */
private static List<String> getRemoteWordsUnprivileged(String location) {

    List<String> buffer = new ArrayList<String>();
    RequestConfig rc = RequestConfig.custom().setConnectionRequestTimeout(10 * 1000).setConnectTimeout(10 * 1000)
            .setSocketTimeout(60 * 1000).build();
    CloseableHttpClient httpclient = HttpClients.createDefault();
    CloseableHttpResponse response;
    BufferedReader in;
    HttpGet get = new HttpGet(location);
    get.setConfig(rc);
    try {
        response = httpclient.execute(get);
        if (response.getStatusLine().getStatusCode() == 200) {

            String charset = "UTF-8";
            // 获取编码,默认为utf-8
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                Header contentType = entity.getContentType();
                if (contentType != null && contentType.getValue() != null) {
                    String typeValue = contentType.getValue();
                    if (typeValue != null && typeValue.contains("charset=")) {
                        charset = typeValue.substring(typeValue.lastIndexOf("=") + 1);
                    }
                }

                if (entity.getContentLength() > 0) {
                    in = new BufferedReader(new InputStreamReader(entity.getContent(), charset));
                    String line;
                    while ((line = in.readLine()) != null) {
                        buffer.add(line);
                    }
                    in.close();
                    response.close();
                    return buffer;
                }
            }
        }
        response.close();
    } catch (IllegalStateException | IOException e) {
        logger.error("getRemoteWords " + location + " error", e);
    }
    return buffer;
}
 
Example 16
Source File: HttpClientResponse.java    From crnk-framework with Apache License 2.0 4 votes vote down vote up
@Override
public String getResponseHeader(String name) {
    Header header = response.getFirstHeader(name);
    return header != null ? header.getValue() : null;
}
 
Example 17
Source File: HttpResponseResource.java    From pushfish-android with BSD 2-Clause "Simplified" License 4 votes vote down vote up
private static String getEtag(HttpResponse response) {
    Header etagHeader = response.getFirstHeader(HttpHeaders.ETAG);
    return etagHeader == null ? null : etagHeader.getValue();
}
 
Example 18
Source File: DownloadThread.java    From mobile-manager-tool with MIT License 4 votes vote down vote up
/**
    * Read headers from the HTTP response and store them into local state.
    */
   private void readResponseHeaders(State state, InnerState innerState,
    HttpResponse response) throws StopRequest {
Header header = response.getFirstHeader("Content-Disposition");
if (header != null) {
    innerState.mHeaderContentDisposition = header.getValue();
}
header = response.getFirstHeader("Content-Location");
if (header != null) {
    innerState.mHeaderContentLocation = header.getValue();
}
if (state.mMimeType == null) {
    header = response.getFirstHeader("Content-Type");
    if (header != null) {
	state.mMimeType = sanitizeMimeType(header.getValue());
    }
}
header = response.getFirstHeader("ETag");
if (header != null) {
    innerState.mHeaderETag = header.getValue();
}
String headerTransferEncoding = null;
header = response.getFirstHeader("Transfer-Encoding");
if (header != null) {
    headerTransferEncoding = header.getValue();
}
if (headerTransferEncoding == null) {
    header = response.getFirstHeader("Content-Length");
    if (header != null) {
	innerState.mHeaderContentLength = header.getValue();
	mInfo.mTotalBytes = Long
		.parseLong(innerState.mHeaderContentLength);
    }
} else {
    // Ignore content-length with transfer-encoding - 2616 4.4 3
    if (Constants.LOGVV) {
	Log.v(Constants.TAG,
		"ignoring content-length because of xfer-encoding");
    }
}
if (Constants.LOGVV) {
    Log.v(Constants.TAG, "Content-Disposition: "
	    + innerState.mHeaderContentDisposition);
    Log.v(Constants.TAG, "Content-Length: "
	    + innerState.mHeaderContentLength);
    Log.v(Constants.TAG, "Content-Location: "
	    + innerState.mHeaderContentLocation);
    Log.v(Constants.TAG, "Content-Type: " + state.mMimeType);
    Log.v(Constants.TAG, "ETag: " + innerState.mHeaderETag);
    Log.v(Constants.TAG, "Transfer-Encoding: " + headerTransferEncoding);
}

boolean noSizeInfo = innerState.mHeaderContentLength == null
	&& (headerTransferEncoding == null || !headerTransferEncoding
		.equalsIgnoreCase("chunked"));
if (!mInfo.mNoIntegrity && noSizeInfo) {
    throw new StopRequest(Downloads.STATUS_HTTP_DATA_ERROR,
	    "can't know size of download, giving up");
}
   }
 
Example 19
Source File: HttpResponseResource.java    From Pushjet-Android with BSD 2-Clause "Simplified" License 4 votes vote down vote up
private static String getEtag(HttpResponse response) {
    Header etagHeader = response.getFirstHeader(HttpHeaders.ETAG);
    return etagHeader == null ? null : etagHeader.getValue();
}
 
Example 20
Source File: ApacheHttpTransaction.java    From OCR-Equation-Solver with MIT License 2 votes vote down vote up
/**
 * Only works for simple headers (ones that do not contain mltiple elements).
 * @param headerName
 * @return
 * @throws IOException
 */
public String getResponseHeader(String headerName) throws IOException {

    Header hdr = response.getFirstHeader(headerName);
    return hdr == null ? null : hdr.getValue();
}