org.apache.http.HeaderElement Java Examples

The following examples show how to use org.apache.http.HeaderElement. 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: HttpWorker.java    From IGUANA with GNU Affero General Public License v3.0 6 votes vote down vote up
public static String getContentTypeVal(Header header) {
    System.out.println("[DEBUG] HEADER: " + header);
    for (HeaderElement el : header.getElements()) {
        NameValuePair cTypePair = el.getParameterByName("Content-Type");

        if (cTypePair != null && !cTypePair.getValue().isEmpty()) {
            return cTypePair.getValue();
        }
    }
    int index = header.toString().indexOf("Content-Type");
    if (index >= 0) {
        String ret = header.toString().substring(index + "Content-Type".length() + 1);
        if (ret.contains(";")) {
            return ret.substring(0, ret.indexOf(";")).trim();
        }
        return ret.trim();
    }
    return "application/sparql-results+json";
}
 
Example #2
Source File: TokenServiceHttpsJwt.java    From api-layer with Eclipse Public License 2.0 6 votes vote down vote up
private String extractToken(CloseableHttpResponse response) throws ZaasClientException, IOException {
    String token = "";
    int httpResponseCode = response.getStatusLine().getStatusCode();
    if (httpResponseCode == 204) {
        HeaderElement[] elements = response.getHeaders("Set-Cookie")[0].getElements();
        Optional<HeaderElement> apimlAuthCookie = Stream.of(elements)
            .filter(element -> element.getName().equals(COOKIE_PREFIX))
            .findFirst();
        if (apimlAuthCookie.isPresent()) {
            token = apimlAuthCookie.get().getValue();
        }
    } else {
        String obtainedMessage = EntityUtils.toString(response.getEntity());
        if (httpResponseCode == 401) {
            throw new ZaasClientException(ZaasClientErrorCodes.INVALID_AUTHENTICATION, obtainedMessage);
        } else if (httpResponseCode == 400) {
            throw new ZaasClientException(ZaasClientErrorCodes.EMPTY_NULL_USERNAME_PASSWORD, obtainedMessage);
        } else {
            throw new ZaasClientException(ZaasClientErrorCodes.GENERIC_EXCEPTION, obtainedMessage);
        }
    }
    return token;
}
 
Example #3
Source File: HttpClientConfig.java    From wecube-platform with Apache License 2.0 6 votes vote down vote up
@Bean
public ConnectionKeepAliveStrategy connectionKeepAliveStrategy() {
    return new ConnectionKeepAliveStrategy() {
        @Override
        public long getKeepAliveDuration(HttpResponse response, HttpContext context) {
            HeaderElementIterator it = new BasicHeaderElementIterator(
                    response.headerIterator(HTTP.CONN_KEEP_ALIVE));
            while (it.hasNext()) {
                HeaderElement he = it.nextElement();
                String param = he.getName();
                String value = he.getValue();

                if (value != null && param.equalsIgnoreCase("timeout")) {
                    return Long.parseLong(value) * 1000;
                }
            }
            return httpClientProperties.getDefaultKeepAliveTimeMillis();
        }
    };
}
 
Example #4
Source File: HttpClientConfig.java    From SpringBootBucket with MIT License 6 votes vote down vote up
@Bean
public ConnectionKeepAliveStrategy connectionKeepAliveStrategy() {
    return new ConnectionKeepAliveStrategy() {
        @Override
        public long getKeepAliveDuration(HttpResponse response, HttpContext httpContext) {
            HeaderElementIterator it = new BasicHeaderElementIterator
                    (response.headerIterator(HTTP.CONN_KEEP_ALIVE));
            while (it.hasNext()) {
                HeaderElement he = it.nextElement();
                String param = he.getName();
                String value = he.getValue();
                if (value != null && param.equalsIgnoreCase("timeout")) {
                    return Long.parseLong(value) * 1000;
                }
            }
            return p.getDefaultKeepAliveTimeMillis();
        }
    };
}
 
Example #5
Source File: EntityUtils.java    From RoboZombie with Apache License 2.0 6 votes vote down vote up
/**
 * Obtains character set of the entity, if known.
 *
 * @param entity must not be null
 * @return the character set, or null if not found
 * @throws ParseException if header elements cannot be deserialized
 * @throws IllegalArgumentException if entity is null
 *
 * @deprecated (4.1.3) use {@link ContentType#getOrDefault(HttpEntity)}
 */
@Deprecated
public static String getContentCharSet(final HttpEntity entity) throws ParseException {
    if (entity == null) {
        throw new IllegalArgumentException("HTTP entity may not be null");
    }
    String charset = null;
    if (entity.getContentType() != null) {
        HeaderElement values[] = entity.getContentType().getElements();
        if (values.length > 0) {
            NameValuePair param = values[0].getParameterByName("charset");
            if (param != null) {
                charset = param.getValue();
            }
        }
    }
    return charset;
}
 
Example #6
Source File: HttpResponseValidationStepsTests.java    From vividus with Apache License 2.0 6 votes vote down vote up
@Test
void testGetHeaderAttributes()
{
    mockHttpResponse();
    Header header = mock(Header.class);
    when(header.getName()).thenReturn(SET_COOKIES_HEADER_NAME);
    httpResponse.setResponseHeaders(header);
    HeaderElement headerElement = mock(HeaderElement.class);
    when(header.getElements()).thenReturn(new HeaderElement[] { headerElement });
    when(softAssert.assertTrue(SET_COOKIES_HEADER_NAME + HEADER_IS_PRESENT, true)).thenReturn(true);
    String headerAttributeName = "HTTPOnly";
    when(headerElement.getName()).thenReturn(headerAttributeName);
    ExamplesTable attribute = new ExamplesTable("|attribute|\n|HTTPOnly|/|");
    httpResponseValidationSteps.assertHeaderContainsAttributes(SET_COOKIES_HEADER_NAME, attribute);
    verify(softAssert).assertThat(
            eq(SET_COOKIES_HEADER_NAME + " header contains " + headerAttributeName + " attribute"),
            eq(Collections.singletonList(headerAttributeName)),
            argThat(matcher -> matcher.toString().equals(Matchers.contains(headerAttributeName).toString())));
}
 
Example #7
Source File: UmaPermissionService.java    From oxTrust with MIT License 6 votes vote down vote up
@Override
public long getKeepAliveDuration(HttpResponse httpResponse, HttpContext httpContext) {

	HeaderElementIterator headerElementIterator = new BasicHeaderElementIterator(
			httpResponse.headerIterator(HTTP.CONN_KEEP_ALIVE));

	while (headerElementIterator.hasNext()) {

		HeaderElement headerElement = headerElementIterator.nextElement();

		String name = headerElement.getName();
		String value = headerElement.getValue();

		if (value != null && name.equalsIgnoreCase("timeout")) {
			return Long.parseLong(value) * 1000;
		}
	}

	// Set own keep alive duration if server does not have it
	return appConfiguration.getRptConnectionPoolCustomKeepAliveTimeout() * 1000;
}
 
Example #8
Source File: HttpResponseValidationSteps.java    From vividus with Apache License 2.0 6 votes vote down vote up
/**
 * Validates that response <b>header</b> contains expected <b>attributes</b>.
 * <p>
 * <b>Actions performed at this step:</b>
 * </p>
 * <ul>
 * <li>Checks that HTTP response header contains expected attributes.</li>
 * </ul>
 * @param httpHeaderName HTTP header name. For example, <b>Content-Type</b>
 * @param attributes expected HTTP header attributes. For example, <b>charset=utf-8</b>
 */
@Then("response header '$httpHeaderName' contains attribute: $attributes")
public void assertHeaderContainsAttributes(String httpHeaderName, ExamplesTable attributes)
{
    performIfHttpResponseIsPresent(response ->
    {
        getHeaderByName(response, httpHeaderName).ifPresent(header ->
        {
            List<String> actualAttributes = Stream.of(header.getElements()).map(HeaderElement::getName)
                    .collect(Collectors.toList());
            for (Parameters row : attributes.getRowsAsParameters(true))
            {
                String expectedAttribute = row.valueAs("attribute", String.class);
                softAssert.assertThat(httpHeaderName + " header contains " + expectedAttribute + " attribute",
                        actualAttributes, contains(expectedAttribute));
            }
        });
    });
}
 
Example #9
Source File: CacheValidityPolicy.java    From apigee-android-sdk with Apache License 2.0 6 votes vote down vote up
protected long getMaxAge(final HttpCacheEntry entry) {
	long maxage = -1;
	for (Header hdr : entry.getHeaders(HeaderConstants.CACHE_CONTROL)) {
		for (HeaderElement elt : hdr.getElements()) {
			if (HeaderConstants.CACHE_CONTROL_MAX_AGE.equals(elt.getName())
					|| "s-maxage".equals(elt.getName())) {
				try {
					long currMaxAge = Long.parseLong(elt.getValue());
					if (maxage == -1 || currMaxAge < maxage) {
						maxage = currMaxAge;
					}
				} catch (NumberFormatException nfe) {
					// be conservative if can't parse
					maxage = 0;
				}
			}
		}
	}
	return maxage;
}
 
Example #10
Source File: SimpleHttpFetcher.java    From ache with Apache License 2.0 6 votes vote down vote up
public long getKeepAliveDuration(HttpResponse response, HttpContext context) {
    if (response == null) {
        throw new IllegalArgumentException("HTTP response may not be null");
    }
    HeaderElementIterator it = new BasicHeaderElementIterator(response.headerIterator(HTTP.CONN_KEEP_ALIVE));
    while (it.hasNext()) {
        HeaderElement he = it.nextElement();
        String param = he.getName();
        String value = he.getValue();
        if (value != null && param.equalsIgnoreCase("timeout")) {
            try {
                return Long.parseLong(value) * 1000;
            } catch (NumberFormatException ignore) {
            }
        }
    }
    return DEFAULT_KEEP_ALIVE_DURATION;
}
 
Example #11
Source File: NUHttpOptions.java    From neembuu-uploader with GNU General Public License v3.0 6 votes vote down vote up
public Set<String> getAllowedMethods(final HttpResponse response) {
    if (response == null) {
        throw new IllegalArgumentException("HTTP response may not be null");
    }

    HeaderIterator it = response.headerIterator("Allow");
    Set<String> methods = new HashSet<String>();
    while (it.hasNext()) {
        Header header = it.nextHeader();
        HeaderElement[] elements = header.getElements();
        for (HeaderElement element : elements) {
            methods.add(element.getName());
        }
    }
    return methods;
}
 
Example #12
Source File: ApacheHttpClientConfig.java    From sfg-blog-posts with GNU General Public License v3.0 6 votes vote down vote up
@Bean
public ConnectionKeepAliveStrategy connectionKeepAliveStrategy() {
  return (httpResponse, httpContext) -> {
    HeaderIterator headerIterator = httpResponse.headerIterator(HTTP.CONN_KEEP_ALIVE);
    HeaderElementIterator elementIterator = new BasicHeaderElementIterator(headerIterator);

    while (elementIterator.hasNext()) {
      HeaderElement element = elementIterator.nextElement();
      String param = element.getName();
      String value = element.getValue();
      if (value != null && param.equalsIgnoreCase("timeout")) {
        return Long.parseLong(value) * 1000; // convert to ms
      }
    }

    return DEFAULT_KEEP_ALIVE_TIME;
  };
}
 
Example #13
Source File: MLabNS.java    From Mobilyzer with Apache License 2.0 6 votes vote down vote up
static private String getContentCharSet(final HttpEntity entity)
    throws ParseException {
  if (entity == null) {
    throw new IllegalArgumentException("entity may not be null");
  }

  String charset = null;
  if (entity.getContentType() != null) {
    HeaderElement values[] = entity.getContentType().getElements();
    if (values.length > 0) {
      NameValuePair param = values[0].getParameterByName("charset");
      if (param != null) {
        charset = param.getValue();
      }
    }
  }
  return charset;
}
 
Example #14
Source File: ProxyServlet.java    From cloud-connectivityproxy with Apache License 2.0 6 votes vote down vote up
private void handleContentEncoding(HttpResponse response) throws ServletException {
	HttpEntity entity = response.getEntity();
	if (entity != null) {
		Header contentEncodingHeader = entity.getContentEncoding();
		if (contentEncodingHeader != null) {
			HeaderElement[] codecs = contentEncodingHeader.getElements();
			LOGGER.debug("Content-Encoding in response:");
			for (HeaderElement codec : codecs) {
				String codecname = codec.getName().toLowerCase();
				LOGGER.debug("    => codec: " + codecname);
				if ("gzip".equals(codecname) || "x-gzip".equals(codecname)) {
					response.setEntity(new GzipDecompressingEntity(response.getEntity()));
					return;
				} else if ("deflate".equals(codecname)) {
					response.setEntity(new DeflateDecompressingEntity(response.getEntity()));
					return;
				} else if ("identity".equals(codecname)) {
					return;
				} else {
					throw new ServletException("Unsupported Content-Encoding: " + codecname);
				}
			}
		}
	}
}
 
Example #15
Source File: HttpClient.java    From hsac-fitnesse-fixtures with Apache License 2.0 6 votes vote down vote up
protected String getAttachmentFileName(org.apache.http.HttpResponse resp) {
    String fileName = null;
    Header[] contentDisp = resp.getHeaders("content-disposition");
    if (contentDisp != null && contentDisp.length > 0) {
        HeaderElement[] headerElements = contentDisp[0].getElements();
        if (headerElements != null) {
            for (HeaderElement headerElement : headerElements) {
                if ("attachment".equals(headerElement.getName())) {
                    NameValuePair param = headerElement.getParameterByName("filename");
                    if (param != null) {
                        fileName = param.getValue();
                        break;
                    }
                }
            }
        }
    }
    return fileName;
}
 
Example #16
Source File: HttpClientResponse.java    From http-api-invoker with MIT License 6 votes vote down vote up
@Override
public Map<String, String> getCookies() {
    Header[] headers = response.getAllHeaders();
    if (headers == null || headers.length == 0) {
        return Collections.emptyMap();
    }
    Map<String, String> map = new HashMap<String, String>();
    for (Header header : headers) {
        if (SET_COOKIE.equalsIgnoreCase(header.getName())) {
            for (HeaderElement element : header.getElements()) {
                map.put(element.getName(), element.getValue());
            }
        }
    }
    return map;
}
 
Example #17
Source File: WebhookMsgHandler.java    From iotplatform with Apache License 2.0 6 votes vote down vote up
@Override
public long getKeepAliveDuration(HttpResponse response, HttpContext context) {
  HeaderElementIterator it = new BasicHeaderElementIterator(response.headerIterator(HTTP.CONN_KEEP_ALIVE));
  while (it.hasNext()) {
    HeaderElement he = it.nextElement();
    String param = he.getName();
    String value = he.getValue();
    if (value != null && param.equalsIgnoreCase("timeout")) {
      long timeout = Long.parseLong(value) * 1000;
      if (timeout > 20 * 1000) {
        return 20 * 1000;
      } else {
        return timeout;
      }
    }
  }
  return 5 * 1000;
}
 
Example #18
Source File: SwiftConnectionManager.java    From stocator with Apache License 2.0 6 votes vote down vote up
@Override
public long getKeepAliveDuration(final HttpResponse response, final HttpContext context) {
  // Honor 'keep-alive' header
  final HeaderElementIterator it = new BasicHeaderElementIterator(
      response.headerIterator(HTTP.CONN_KEEP_ALIVE));
  while (it.hasNext()) {
    final HeaderElement he = it.nextElement();
    final String param = he.getName();
    final String value = he.getValue();
    if (value != null && param.equalsIgnoreCase("timeout")) {
      try {
        return Long.parseLong(value) * 1000;
      } catch (NumberFormatException ignore) {
        // Do nothing
      }
    }
  }
  // otherwise keep alive for 30 seconds
  return 30 * 1000;
}
 
Example #19
Source File: SPARQLProtocolSession.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private static boolean contentTypeIs(HttpResponse response, String contentType) {
	Header[] headers = response.getHeaders("Content-Type");
	if (headers.length == 0) {
		return false;
	}

	for (Header header : headers) {
		for (HeaderElement element : header.getElements()) {
			String name = element.getName().split("\\+")[0];
			if (contentType.equals(name)) {
				return true;
			}
		}
	}

	return false;
}
 
Example #20
Source File: SPARQLProtocolSession.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Gets the MIME type specified in the response headers of the supplied method, if any. For example, if the response
 * headers contain <tt>Content-Type: application/xml;charset=UTF-8</tt>, this method will return
 * <tt>application/xml</tt> as the MIME type.
 *
 * @param method The method to get the reponse MIME type from.
 * @return The response MIME type, or <tt>null</tt> if not available.
 */
protected String getResponseMIMEType(HttpResponse method) throws IOException {
	Header[] headers = method.getHeaders("Content-Type");

	for (Header header : headers) {
		HeaderElement[] headerElements = header.getElements();

		for (HeaderElement headerEl : headerElements) {
			String mimeType = headerEl.getName();
			if (mimeType != null) {
				logger.debug("response MIME type is {}", mimeType);
				return mimeType;
			}
		}
	}

	return null;
}
 
Example #21
Source File: HttpClientKeepAliveStrategy.java    From disconf with Apache License 2.0 6 votes vote down vote up
@Override
public long getKeepAliveDuration(HttpResponse response, HttpContext context) {
    HeaderElementIterator it = new BasicHeaderElementIterator(
            response.headerIterator(HTTP.CONN_KEEP_ALIVE));
    while (it.hasNext()) {
        HeaderElement he = it.nextElement();
        String param = he.getName();
        String value = he.getValue();
        if (value != null && param.equalsIgnoreCase("timeout")) {
            try {
                return Long.parseLong(value) * 1000;
            } catch (NumberFormatException ignore) {
            }
        }
    }
    return keepAliveTimeOut * 1000;
}
 
Example #22
Source File: ClickHouseHttpClientBuilder.java    From clickhouse-jdbc with Apache License 2.0 6 votes vote down vote up
private ConnectionKeepAliveStrategy createKeepAliveStrategy() {
    return new ConnectionKeepAliveStrategy() {
        @Override
        public long getKeepAliveDuration(HttpResponse httpResponse, HttpContext httpContext) {
            // in case of errors keep-alive not always works. close connection just in case
            if (httpResponse.getStatusLine().getStatusCode() != HttpURLConnection.HTTP_OK) {
                return -1;
            }
            HeaderElementIterator it = new BasicHeaderElementIterator(
                    httpResponse.headerIterator(HTTP.CONN_DIRECTIVE));
            while (it.hasNext()) {
                HeaderElement he = it.nextElement();
                String param = he.getName();
                //String value = he.getValue();
                if (param != null && param.equalsIgnoreCase(HTTP.CONN_KEEP_ALIVE)) {
                    return properties.getKeepAliveTimeout();
                }
            }
            return -1;
        }
    };
}
 
Example #23
Source File: ApiClientResponseTest.java    From amex-api-java-client-core with Apache License 2.0 6 votes vote down vote up
@Test
public void valid() {
    Header[] headers = {new Header() {
        public String getName() {
            return "session_id";
        }

        public String getValue() {
            return "12345";
        }

        public HeaderElement[] getElements() throws ParseException {
            return new HeaderElement[0];
        }
    }};
    ApiClientResponse response = new ApiClientResponse(headers, "{\"key\":\"value\"}");

    assertEquals("12345", response.getHeader("session_id"));
    assertEquals("{\n  \"key\" : \"value\"\n}", response.toJson());
    assertEquals("value", response.getField("key"));
}
 
Example #24
Source File: ApacheGatewayConnectionTest.java    From vespa with Apache License 2.0 6 votes vote down vote up
private HttpResponse httpResponse(String sessionIdInResult, String version) throws IOException {
    final HttpResponse httpResponseMock = mock(HttpResponse.class);

    StatusLine statusLineMock = mock(StatusLine.class);
    when(httpResponseMock.getStatusLine()).thenReturn(statusLineMock);
    when(statusLineMock.getStatusCode()).thenReturn(200);

    addMockedHeader(httpResponseMock, Headers.SESSION_ID, sessionIdInResult, null);
    addMockedHeader(httpResponseMock, Headers.VERSION, version, null);
    HeaderElement[] headerElements = new HeaderElement[1];
    headerElements[0] = mock(HeaderElement.class);

    final HttpEntity httpEntityMock = mock(HttpEntity.class);
    when(httpResponseMock.getEntity()).thenReturn(httpEntityMock);

    final InputStream inputs = new ByteArrayInputStream("fake response data".getBytes());

    when(httpEntityMock.getContent()).thenReturn(inputs);
    return httpResponseMock;
}
 
Example #25
Source File: OtherUtils.java    From android-open-project-demo with Apache License 2.0 6 votes vote down vote up
public static Charset getCharsetFromHttpRequest(final HttpRequestBase request) {
    if (request == null) return null;
    String charsetName = null;
    Header header = request.getFirstHeader("Content-Type");
    if (header != null) {
        for (HeaderElement element : header.getElements()) {
            NameValuePair charsetPair = element.getParameterByName("charset");
            if (charsetPair != null) {
                charsetName = charsetPair.getValue();
                break;
            }
        }
    }

    boolean isSupportedCharset = false;
    if (!TextUtils.isEmpty(charsetName)) {
        try {
            isSupportedCharset = Charset.isSupported(charsetName);
        } catch (Throwable e) {
        }
    }

    return isSupportedCharset ? Charset.forName(charsetName) : null;
}
 
Example #26
Source File: OtherUtils.java    From android-open-project-demo with Apache License 2.0 6 votes vote down vote up
public static String getFileNameFromHttpResponse(final HttpResponse response) {
    if (response == null) return null;
    String result = null;
    Header header = response.getFirstHeader("Content-Disposition");
    if (header != null) {
        for (HeaderElement element : header.getElements()) {
            NameValuePair fileNamePair = element.getParameterByName("filename");
            if (fileNamePair != null) {
                result = fileNamePair.getValue();
                // try to get correct encoding str
                result = CharsetUtils.toCharset(result, HTTP.UTF_8, result.length());
                break;
            }
        }
    }
    return result;
}
 
Example #27
Source File: ApacheGatewayConnectionTest.java    From vespa with Apache License 2.0 6 votes vote down vote up
private void addMockedHeader(
        final HttpResponse httpResponseMock,
        final String name,
        final String value,
        HeaderElement[] elements) {
    final Header header = new Header() {
        @Override
        public String getName() {
            return name;
        }
        @Override
        public String getValue() {
            return value;
        }
        @Override
        public HeaderElement[] getElements() throws ParseException {
            return elements;
        }
    };
    when(httpResponseMock.getFirstHeader(name)).thenReturn(header);
}
 
Example #28
Source File: OtherUtils.java    From BigApp_Discuz_Android with Apache License 2.0 6 votes vote down vote up
public static String getFileNameFromHttpResponse(final HttpResponse response) {
    if (response == null) return null;
    String result = null;
    Header header = response.getFirstHeader("Content-Disposition");
    if (header != null) {
        for (HeaderElement element : header.getElements()) {
            NameValuePair fileNamePair = element.getParameterByName("filename");
            if (fileNamePair != null) {
                result = fileNamePair.getValue();
                // try to get correct encoding str
                result = CharsetUtils.toCharset(result, HTTP.UTF_8, result.length());
                break;
            }
        }
    }
    return result;
}
 
Example #29
Source File: HttpClientKeepAliveStrategy.java    From disconf with Apache License 2.0 6 votes vote down vote up
@Override
public long getKeepAliveDuration(HttpResponse response, HttpContext context) {
    HeaderElementIterator it = new BasicHeaderElementIterator(
            response.headerIterator(HTTP.CONN_KEEP_ALIVE));
    while (it.hasNext()) {
        HeaderElement he = it.nextElement();
        String param = he.getName();
        String value = he.getValue();
        if (value != null && param.equalsIgnoreCase("timeout")) {
            try {
                return Long.parseLong(value) * 1000;
            } catch (NumberFormatException ignore) {
            }
        }
    }
    return keepAliveTimeOut * 1000;
}
 
Example #30
Source File: HttpClient4EntityExtractor.java    From pinpoint with Apache License 2.0 6 votes vote down vote up
/**
 * copy: EntityUtils Obtains character set of the entity, if known.
 *
 * @param entity must not be null
 * @return the character set, or null if not found
 * @throws ParseException           if header elements cannot be parsed
 * @throws IllegalArgumentException if entity is null
 */
private static String getContentCharSet(final HttpEntity entity) throws ParseException {
    if (entity == null) {
        throw new IllegalArgumentException("HTTP entity must not be null");
    }
    String charset = null;
    if (entity.getContentType() != null) {
        HeaderElement values[] = entity.getContentType().getElements();
        if (values.length > 0) {
            NameValuePair param = values[0].getParameterByName("charset");
            if (param != null) {
                charset = param.getValue();
            }
        }
    }
    return charset;
}