Java Code Examples for org.apache.http.entity.ContentType#getOrDefault()

The following examples show how to use org.apache.http.entity.ContentType#getOrDefault() . 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: AbstractResponseHandler.java    From iBioSim with Apache License 2.0 6 votes vote down vote up
protected T parseResponse(StatusLine statusLine, HttpEntity entity, Class<T> pojoClass)
        throws IOException {
    if (statusLine.getStatusCode() >= 400) {
        throw new HttpResponseException(
                statusLine.getStatusCode(),
                statusLine.getReasonPhrase());
    }
    if (entity == null) {
        throw new ClientProtocolException("Response contains no content");
    }
    ContentType contentType = ContentType.getOrDefault(entity);
    Charset charset = contentType.getCharset() != null ? contentType.getCharset() :
            StandardCharsets.UTF_8;

    try (BufferedReader reader = new BufferedReader(
            new InputStreamReader(entity.getContent(), charset))) {
        return unmarshallContent(reader, pojoClass);
    }
}
 
Example 2
Source File: AbsoluteReferenceResolver.java    From apicurio-studio with Apache License 2.0 6 votes vote down vote up
/**
 * @see io.apicurio.hub.api.content.AbstractReferenceResolver#fetchUriContent(java.net.URI)
 */
@Override
protected String fetchUriContent(URI referenceUri) throws IOException {
    HttpGet get = new HttpGet(referenceUri);
    try (CloseableHttpResponse response = httpClient.execute(get)) {
        if (response.getStatusLine().getStatusCode() < 200 || response.getStatusLine().getStatusCode() > 299) {
            return null;
        }
        try (InputStream contentStream = response.getEntity().getContent()) {
            ContentType ct = ContentType.getOrDefault(response.getEntity());
            String encoding = StandardCharsets.UTF_8.name();
            if (ct != null && ct.getCharset() != null) {
                encoding = ct.getCharset().name();
            }
            return IOUtils.toString(contentStream, encoding);
        }
    }
}
 
Example 3
Source File: CheckmobiValidationClient.java    From tigase-extension with GNU General Public License v3.0 6 votes vote down vote up
private JsonObject parseResponse(CloseableHttpResponse res) throws IOException {
    try {
        if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            HttpEntity entity = res.getEntity();
            if (entity != null) {
                ContentType contentType = ContentType.getOrDefault(entity);
                Charset charset = contentType.getCharset();
                if (charset == null)
                    charset = Charset.forName("UTF-8");
                Reader reader = new InputStreamReader(entity.getContent(), charset);
                return (JsonObject) new JsonParser().parse(reader);
            }

            // no response body
            return new JsonObject();
        }
        else
            throw new HttpResponseException(
                    res.getStatusLine().getStatusCode(),
                    res.getStatusLine().getReasonPhrase());
    }
    finally {
        res.close();
    }
}
 
Example 4
Source File: SimpleUrlFetcher.java    From seldon-server with Apache License 2.0 5 votes vote down vote up
@Override
public String getUrl(String url) throws Exception {
    String response_content = "";

    HttpClient httpclient = new DefaultHttpClient();
    httpclient.getParams().setParameter(CoreProtocolPNames.USER_AGENT, "Mozilla/5.0 (Macintosh;) SeldonBot/1.0");
    httpclient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, httpGetTimeout);
    httpclient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, httpGetTimeout);
    
    try {
        HttpGet httpget = new HttpGet( url );
        httpget.addHeader("Connection", "close");
        HttpResponse response = httpclient.execute(httpget);
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            ContentType contentType = ContentType.getOrDefault(entity);
            logger.info("Response contentType: "+contentType);
            
            String contentCharSet = EntityUtils.getContentCharSet(entity);              
            logger.info("Response contentCharSet: "+contentCharSet);
            
            response_content = EntityUtils.toString(entity);
            EntityUtils.consume(entity);
        }
    } catch (Exception e) {
        throw e;
    } finally {
        httpclient.getConnectionManager().closeExpiredConnections();
        httpclient.getConnectionManager().closeIdleConnections(30, TimeUnit.SECONDS);
        httpclient.getConnectionManager().shutdown();
    }
    
    return response_content;
}
 
Example 5
Source File: HttpConnHelper.java    From QiQuYingServer with Apache License 2.0 5 votes vote down vote up
/**
 * 创建响应处理器ResponseHandler
 * 
 * @return
 */
public static <T> ResponseHandler<T> prepareResponseHandler(final Class<T> c) {
	ResponseHandler<T> rh = new ResponseHandler<T>() {
		@Override
		public T handleResponse(final HttpResponse response)
				throws IOException {

			StatusLine statusLine = response.getStatusLine();
			HttpEntity entity = response.getEntity();
			if (statusLine.getStatusCode() >= 300) {
				throw new HttpResponseException(statusLine.getStatusCode(),
						statusLine.getReasonPhrase());
			}
			if (entity == null) {
				throw new ClientProtocolException(
						"Response contains no content");
			}
			ContentType contentType = ContentType.getOrDefault(entity);
			Charset charset = contentType.getCharset();
			Reader reader = new InputStreamReader(entity.getContent(),
					charset);
			long hand_start = System.currentTimeMillis();
			T t = gson.fromJson(reader, c);
			long hand_end = System.currentTimeMillis();
			double cost = (hand_end-hand_start)/1000.0;
			log.info("handleResponse convert cost time "+cost+"s");
			return t;
		}
	};
	return rh;
}
 
Example 6
Source File: CognalysVerifyClient.java    From tigase-extension with GNU General Public License v3.0 5 votes vote down vote up
private JsonObject _get(String url, List<NameValuePair> params) throws IOException {
    URI uri;
    try {
        uri = new URIBuilder(url)
                .addParameters(params)
                // add authentication parameters
                .addParameter("app_id", appId)
                .addParameter("access_token", token)
                .build();
    }
    catch (URISyntaxException e) {
        throw new IOException("Invalid URL", e);
    }
    HttpGet req = new HttpGet(uri);
    CloseableHttpResponse res = client.execute(req);
    try {
        if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            HttpEntity entity = res.getEntity();
            if (entity != null) {
                ContentType contentType = ContentType.getOrDefault(entity);
                Charset charset = contentType.getCharset();
                if (charset == null)
                    charset = Charset.forName("UTF-8");
                Reader reader = new InputStreamReader(entity.getContent(), charset);
                return (JsonObject) new JsonParser().parse(reader);
            }

            // no response body
            return new JsonObject();
        }
        else
            throw new HttpResponseException(
                    res.getStatusLine().getStatusCode(),
                    res.getStatusLine().getReasonPhrase());
    }
    finally {
        res.close();
    }
}
 
Example 7
Source File: HttpResponseHandler.java    From iaf with Apache License 2.0 5 votes vote down vote up
public ContentType getContentType() {
	Header contentTypeHeader = this.getFirstHeader(HttpHeaders.CONTENT_TYPE);
	ContentType contentType;
	if (contentTypeHeader != null) {
		contentType = ContentType.parse(contentTypeHeader.getValue());
	} else {
		contentType = ContentType.getOrDefault(httpEntity);
	}
	return contentType;
}
 
Example 8
Source File: Webdav4FileObject.java    From commons-vfs with Apache License 2.0 5 votes vote down vote up
DavPropertySet getProperties(final GenericURLFileName name, final int type, final DavPropertyNameSet nameSet,
        final boolean addEncoding) throws FileSystemException {
    try {
        final String urlStr = toUrlString(name);
        final HttpPropfind request = new HttpPropfind(urlStr, type, nameSet, DavConstants.DEPTH_0);
        setupRequest(request);
        final HttpResponse res = executeRequest(request);
        if (request.succeeded(res)) {
            final MultiStatus multiStatus = request.getResponseBodyAsMultiStatus(res);
            final MultiStatusResponse response = multiStatus.getResponses()[0];
            final DavPropertySet props = response.getProperties(HttpStatus.SC_OK);
            if (addEncoding) {
                final ContentType resContentType = ContentType.getOrDefault(res.getEntity());
                final DavProperty prop = new DefaultDavProperty(RESPONSE_CHARSET,
                        resContentType.getCharset().name());
                props.add(prop);
            }
            return props;
        }
        return new DavPropertySet();
    } catch (final FileSystemException fse) {
        throw fse;
    } catch (final Exception e) {
        throw new FileSystemException("vfs.provider.webdav/get-property.error", e, getName(), name, type,
                nameSet.getContent(), addEncoding);
    }
}
 
Example 9
Source File: BingSearchResults.java    From act with GNU General Public License v3.0 4 votes vote down vote up
/** This function issues a Bing search API call and gets the JSONObject containing the relevant results
 * (including TotalCounts and SearchResults)
 * @param queryTerm (String) the term to query for.
 * @param count (int) URL parameter indicating how many results to return. Max value is 100.
 * @param offset (int) URL parameter indicating the offset for results.
 * @return a JSONObject containing the response.
 * @throws IOException
 */
private JsonNode fetchBingSearchAPIResponse(String queryTerm, Integer count, Integer offset) throws IOException {

  if (count <= 0) {
    LOGGER.error("Bing Search API was called with \"count\" URL parameter = 0. Please request at least one result.");
    return null;
  }

  URI uri = null;
  try {
    // Bing URL pattern. Note that we use composite queries to allow retrieval of the total results count.
    // Transaction cost is [count] bings, where [count] is the value of the URL parameter "count".
    // In other words, we can make 5M calls with [count]=1 per month.


    // Example: https://api.cognitive.microsoft.com/bing/v5.0/search?q=porsche&responseFilter=webpages
    uri = new URIBuilder()
        .setScheme("https")
        .setHost(BING_API_HOST)
        .setPath(BING_API_PATH)
        // Wrap the query term (%s) with double quotes (%%22) for exact search
        .setParameter("q", String.format("%s", queryTerm))
        // Restrict response to Web Pages only
        .setParameter("responseFilter", "webpages")
        // "count" parameter.
        .setParameter("count", count.toString())
        // "offset" parameter.
        .setParameter("offset", offset.toString())
        .build();

  } catch (URISyntaxException e) {
    LOGGER.error("An error occurred when trying to build the Bing Search API URI", e);
  }

  JsonNode results;
  HttpGet httpget = new HttpGet(uri);
  // Yay for un-encrypted account key!
  // TODO: actually is there a way to encrypt it?
  httpget.setHeader("Ocp-Apim-Subscription-Key", accountKey);

  CloseableHttpClient httpclient = HttpClients.custom().setConnectionManager(basicConnManager).build();

  try (CloseableHttpResponse response = httpclient.execute(httpget)) {
    Integer statusCode = response.getStatusLine().getStatusCode();

    // TODO: The Web Search API returns useful error messages, we could use them to have better insights on failures.
    // See: https://dev.cognitive.microsoft.com/docs/services/56b43eeccf5ff8098cef3807/operations/56b4447dcf5ff8098cef380d
    if (!statusCode.equals(HttpStatus.SC_OK)) {
      LOGGER.error("Bing Search API call returned an unexpected status code (%d) for URI: %s", statusCode, uri);
      return null;
    }

    HttpEntity entity = response.getEntity();
    ContentType contentType = ContentType.getOrDefault(entity);
    Charset charset = contentType.getCharset();
    if (charset == null) {
      charset = StandardCharsets.UTF_8;
    }

    try (final BufferedReader in = new BufferedReader(new InputStreamReader(entity.getContent(), charset))) {
      String inputLine;
      final StringBuilder stringResponse = new StringBuilder();
      while ((inputLine = in.readLine()) != null) {
        stringResponse.append(inputLine);
      }
      JsonNode rootNode = mapper.readValue(stringResponse.toString(), JsonNode.class);
      results = rootNode.path("webPages");
    }
  }
  return results;
}
 
Example 10
Source File: AbstractUriExplorer.java    From timbuctoo with GNU General Public License v3.0 4 votes vote down vote up
static String getCharset(HttpResponse response) {
  ContentType contentType = ContentType.getOrDefault(response.getEntity());
  Charset charset = contentType.getCharset();
  return charset == null ? "UTF-8" : charset.name();
}