Java Code Examples for org.apache.http.HttpResponse#getEntity()

The following examples show how to use org.apache.http.HttpResponse#getEntity() . 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: HttpClientUtil.java    From hermes with Apache License 2.0 6 votes vote down vote up
/**
 * https get请求
 * @param url
 * @return
 * @throws Exception
 */
public static String doGetHttps(String url) throws  Exception {
	initSSLContext();
	StringBuilder stringBuilder = new StringBuilder();
	HttpGet httpGet = new HttpGet(url);
	HttpResponse response = httpClient.execute(httpGet);
	int responseCode = response.getStatusLine().getStatusCode();
	Logger.info("httpClient get 响应状态responseCode="+responseCode+", 请求 URL="+url);
	HttpEntity respEntity = response.getEntity();
	BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(respEntity.getContent(), "UTF-8"));
	String text;
	if(responseCode == RSP_200 || responseCode == RSP_400){
		while ((text = bufferedReader.readLine()) != null) {
			stringBuilder.append(text);
		}
	}else{
		throw new Exception("接口请求异常:接口响应状态="+responseCode);
	}
	bufferedReader.close();
	httpGet.releaseConnection();
	return stringBuilder.toString();
}
 
Example 2
Source File: PlainDeserializer.java    From RoboZombie with Apache License 2.0 6 votes vote down vote up
/**
 * <p>Deserializes the response content to a type which is assignable to {@link CharSequence}.</p>
 * 
 * @see AbstractDeserializer#run(InvocationContext, HttpResponse)
 */
@Override
public CharSequence deserialize(InvocationContext context, HttpResponse response) {

	try {
		
		HttpEntity entity = response.getEntity();
		return entity == null? "" :EntityUtils.toString(entity);
	} 
	catch(Exception e) {
		
		throw new DeserializerException(new StringBuilder("Plain deserialization failed for request <")
		.append(context.getRequest().getName())
		.append("> on endpoint <")
		.append(context.getEndpoint().getName())
		.append(">").toString(), e);
	}
}
 
Example 3
Source File: CardcastService.java    From PYX-Reloaded with Apache License 2.0 6 votes vote down vote up
@Nullable
private String getUrlContent(String urlStr) throws IOException {
    HttpResponse resp = client.execute(new HttpGet(urlStr));

    StatusLine sl = resp.getStatusLine();
    if (sl.getStatusCode() != HttpStatus.SC_OK) {
        LOG.error(String.format("Got HTTP response code %s from Cardcast for %s", sl, urlStr));
        return null;
    }

    HttpEntity entity = resp.getEntity();
    String contentType = entity.getContentType().getValue();
    if (!Objects.equals(contentType, "application/json")) {
        LOG.error(String.format("Got content-type %s from Cardcast for %s", contentType, urlStr));
        return null;
    }

    return EntityUtils.toString(entity);
}
 
Example 4
Source File: CustomerDatabaseClient.java    From keycloak with Apache License 2.0 6 votes vote down vote up
public static List<String> getCustomers(HttpServletRequest req) throws Failure {
    KeycloakSecurityContext session = (KeycloakSecurityContext) req.getAttribute(KeycloakSecurityContext.class.getName());

    HttpClient client = new DefaultHttpClient();
    try {
        HttpGet get = new HttpGet(UriUtils.getOrigin(req.getRequestURL().toString()) + "/database/customers");
        get.addHeader("Authorization", "Bearer " + session.getTokenString());
        try {
            HttpResponse response = client.execute(get);
            if (response.getStatusLine().getStatusCode() != 200) {
                throw new Failure(response.getStatusLine().getStatusCode());
            }
            HttpEntity entity = response.getEntity();
            InputStream is = entity.getContent();
            try {
                return JsonSerialization.readValue(is, TypedList.class);
            } finally {
                is.close();
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    } finally {
        client.getConnectionManager().shutdown();
    }
}
 
Example 5
Source File: GerritRestClient.java    From gerrit-rest-java-client with Apache License 2.0 6 votes vote down vote up
@Override
public JsonElement requestJson(String path, String requestBody, HttpVerb verb) throws RestApiException {
    try {
        HttpResponse response = requestRest(path, requestBody, verb);

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

        checkContentType(entity);

        JsonElement ret = parseResponse(entity.getContent());
        if (ret.isJsonNull()) {
            throw new RestApiException("Unexpectedly empty response.");
        }
        return ret;
    } catch (IOException e) {
        throw new RestApiException("Request failed.", e);
    }
}
 
Example 6
Source File: BaseClient.java    From galaxy-sdk-java with Apache License 2.0 6 votes vote down vote up
public <T> Object processResponse(HttpResponse response, Class<T> c, String purposeStr)
    throws IOException {
  HttpEntity httpEntity = response.getEntity();
  int statusCode = response.getStatusLine().getStatusCode();
  try {
    if (statusCode == HttpStatus.SC_OK) {
      if (c != null) {
        Reader reader = new InputStreamReader(httpEntity.getContent());
        T entityVal = new Gson().fromJson(reader, c);
        return entityVal;
      }
      return null;
    } else {
      String errorMsg = formatErrorMsg(purposeStr, response);
      LOG.error(errorMsg);
      throw new IOException(errorMsg);
    }
  } catch (IOException e) {
    LOG.error("read response entity", e);
    throw new IOException("read response entity", e);
  } finally {
    closeResponseEntity(response);
  }
}
 
Example 7
Source File: HttpUtil.java    From keycloak with Apache License 2.0 6 votes vote down vote up
InputStream doGet(String acceptType, String... path) throws ClientRegistrationException {
    try {
        HttpGet request = new HttpGet(getUrl(baseUri, path));

        request.setHeader(HttpHeaders.ACCEPT, acceptType);

        addAuth(request);

        HttpResponse response = httpClient.execute(request);
        InputStream responseStream = null;
        if (response.getEntity() != null) {
            responseStream = response.getEntity().getContent();
        }

        if (response.getStatusLine().getStatusCode() == 200) {
            return responseStream;
        } else if (response.getStatusLine().getStatusCode() == 404) {
            responseStream.close();
            return null;
        } else {
            throw httpErrorException(response, responseStream);
        }
    } catch (IOException e) {
        throw new ClientRegistrationException("Failed to send request", e);
    }
}
 
Example 8
Source File: NFHttpClientTest.java    From ribbon with Apache License 2.0 5 votes vote down vote up
@Test
public void testDefaultClient() throws Exception {
	NFHttpClient client = NFHttpClientFactory.getDefaultClient();
	HttpGet get = new HttpGet(server.getServerURI()); // uri
	// this is not the overridable method
	HttpResponse response = client.execute(get);
	HttpEntity entity = response.getEntity();
	String contentStr = EntityUtils.toString(entity);
	assertTrue(contentStr.length() > 0);
}
 
Example 9
Source File: HttpHealthcareApiClient.java    From beam with Apache License 2.0 5 votes vote down vote up
@Override
public HttpBody executeFhirBundle(String fhirStore, String bundle)
    throws IOException, HealthcareHttpException {
  if (httpClient == null || client == null) {
    initClient();
  }

  credentials.refreshIfExpired();
  StringEntity requestEntity = new StringEntity(bundle, ContentType.APPLICATION_JSON);
  URI uri;
  try {
    uri = new URIBuilder(client.getRootUrl() + "v1beta1/" + fhirStore + "/fhir").build();
  } catch (URISyntaxException e) {
    LOG.error("URL error when making executeBundle request to FHIR API. " + e.getMessage());
    throw new IllegalArgumentException(e);
  }

  HttpUriRequest request =
      RequestBuilder.post()
          .setUri(uri)
          .setEntity(requestEntity)
          .addHeader("Authorization", "Bearer " + credentials.getAccessToken().getTokenValue())
          .addHeader("User-Agent", USER_AGENT)
          .addHeader("Content-Type", FHIRSTORE_HEADER_CONTENT_TYPE)
          .addHeader("Accept-Charset", FHIRSTORE_HEADER_ACCEPT_CHARSET)
          .addHeader("Accept", FHIRSTORE_HEADER_ACCEPT)
          .build();

  HttpResponse response = httpClient.execute(request);
  HttpEntity responseEntity = response.getEntity();
  String content = EntityUtils.toString(responseEntity);

  // Check 2XX code.
  if (!(response.getStatusLine().getStatusCode() / 100 == 2)) {
    throw HealthcareHttpException.of(response);
  }
  HttpBody responseModel = new HttpBody();
  responseModel.setData(content);
  return responseModel;
}
 
Example 10
Source File: DS937BoxcarringTestCase.java    From product-ei with Apache License 2.0 5 votes vote down vote up
public Object[] sendPOST(String endpoint, String content, Map<String, String> headers) throws IOException {
    HttpClient httpClient = new DefaultHttpClient();
    httpClient.getParams().setParameter("http.socket.timeout", 120000);
    HttpPost httpPost = new HttpPost(endpoint);

    if(sessionID == null) {
        sessionID = "11";
    }
    headers.put("Cookie",sessionID);
    for (String headerType : headers.keySet()) {
        httpPost.setHeader(headerType, headers.get(headerType));
    }
    if (content != null) {
        HttpEntity httpEntity = new ByteArrayEntity(content.getBytes("UTF-8"));
        if (headers.get("Content-Type") == null) {
            httpPost.setHeader("Content-Type", "application/json");
        }
        httpPost.setEntity(httpEntity);
    }
    HttpResponse httpResponse = httpClient.execute(httpPost);
    Header[] responseHeaders = httpResponse.getHeaders("Set-Cookie");
    if (responseHeaders != null && responseHeaders.length > 0) {
        sessionID = responseHeaders[0].getValue();
    }
    if (httpResponse.getEntity() != null) {
        BufferedReader reader = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent()));
        String inputLine;
        StringBuilder response = new StringBuilder();
        while ((inputLine = reader.readLine()) != null) {
            response.append(inputLine);
        }
        reader.close();
        return new Object[] { httpResponse.getStatusLine().getStatusCode(), response.toString() };
    } else {
        return new Object[] { httpResponse.getStatusLine().getStatusCode() };
    }
}
 
Example 11
Source File: HttpUtil.java    From wechat-mp-sdk with Apache License 2.0 5 votes vote down vote up
@Override
public String handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
    final StatusLine statusLine = response.getStatusLine();
    if (statusLine.getStatusCode() >= 300) {
        throw new HttpResponseException(statusLine.getStatusCode(), statusLine.getReasonPhrase());
    }

    final HttpEntity entity = response.getEntity();
    if (entity != null) {
        return EntityUtils.toString(entity, "UTF-8");
    }

    return StringUtils.EMPTY;
}
 
Example 12
Source File: SDKConnection.java    From BotLibre with Eclipse Public License 1.0 5 votes vote down vote up
public String GET(String url) {
	if (this.debug) {
		System.out.println("GET: " + url);
	}
	String xml = null;
	try {
		HttpClient httpClient = new DefaultHttpClient();
		HttpContext localContext = new BasicHttpContext();
		HttpGet httpGet = new HttpGet(url);
		HttpResponse response = httpClient.execute(httpGet, localContext);
		HttpEntity entity = response.getEntity();
		xml = EntityUtils.toString(entity, HTTP.UTF_8);

		if (response.getStatusLine().getStatusCode() != 200) {
			this.exception = new SDKException(""
			   + response.getStatusLine().getStatusCode()
			   + " : " + xml);
			return "";
		}
	} catch (Exception exception) {
		if (this.debug) {
			exception.printStackTrace();
		}
		this.exception = new SDKException(exception);
		throw this.exception;
	}
	return xml;
}
 
Example 13
Source File: HttpClientDelegate.java    From wechat-sdk with Apache License 2.0 5 votes vote down vote up
@Override
public String handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
    int status = response.getStatusLine().getStatusCode();
    if (status >= 200 && status < 300) {
        HttpEntity entity = response.getEntity();
        String str = EntityUtils.toString(entity,"UTF-8");
        LOGGER.debug("Get response: " + str);
        return str;
    } else {
        throw new ClientProtocolException("Unexpected response status:" + status);
    }
}
 
Example 14
Source File: KaiXinResponseHandler.java    From YiBo with Apache License 2.0 5 votes vote down vote up
public String handleResponse(final HttpResponse response) throws HttpResponseException, IOException {
	StatusLine statusLine = response.getStatusLine();
	HttpEntity entity = response.getEntity();
	String responseString = (entity == null ? null : EntityUtils.toString(entity));

	Logger.debug("KaiXinResponseHandler : {}", responseString);

	if (responseString != null
		&& responseString.contains("error_code")
		&& responseString.startsWith("{")) {
		try {
			JSONObject json = new JSONObject(responseString);
			if (json.has("error_code")) {
				// 明确是异常响应,而不是包含了error_code的文本
				int errorCode = json.getInt("error_code");
				String errorDesc = json.getString("error");
				String requestPath = json.getString("request");
				throw new LibRuntimeException(
					errorCode, requestPath,	errorDesc, ServiceProvider.KaiXin);
			}
		} catch (JSONException e) {
			throw new LibRuntimeException(LibResultCode.JSON_PARSE_ERROR, e, ServiceProvider.RenRen);
		}
	}

	int statusCode = statusLine.getStatusCode();
	if (statusCode >= 300) {
		throw new HttpResponseException(statusLine.getStatusCode(), statusLine.getReasonPhrase());
	}

	return responseString;
}
 
Example 15
Source File: ResponseSender.java    From esigate with Apache License 2.0 5 votes vote down vote up
void sendHeaders(HttpResponse httpResponse, IncomingRequest httpRequest, HttpServletResponse response) {
    response.setStatus(httpResponse.getStatusLine().getStatusCode());
    for (Header header : httpResponse.getAllHeaders()) {
        String name = header.getName();
        String value = header.getValue();
        response.addHeader(name, value);
    }

    // Copy new cookies
    Cookie[] newCookies = httpRequest.getNewCookies();

    for (Cookie newCooky : newCookies) {

        // newCooky may be null. In that case just ignore.
        // See https://github.com/esigate/esigate/issues/181
        if (newCooky != null) {
            response.addHeader("Set-Cookie", CookieUtil.encodeCookie(newCooky));
        }
    }
    HttpEntity httpEntity = httpResponse.getEntity();
    if (httpEntity != null) {
        long contentLength = httpEntity.getContentLength();
        if (contentLength > -1 && contentLength < Integer.MAX_VALUE) {
            response.setContentLength((int) contentLength);
        }
        Header contentType = httpEntity.getContentType();
        if (contentType != null) {
            response.setContentType(contentType.getValue());
        }
        Header contentEncoding = httpEntity.getContentEncoding();
        if (contentEncoding != null) {
            response.setHeader(contentEncoding.getName(), contentEncoding.getValue());
        }
    }
}
 
Example 16
Source File: HttpClientUtils.java    From EosProxyServer with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * 从 response 里获取 charset
 *
 * @param ressponse
 * @return
 */
@SuppressWarnings("unused")
private static String getCharsetFromResponse(HttpResponse ressponse) {
    // Content-Type:text/html; charset=GBK
    if (ressponse.getEntity() != null  && ressponse.getEntity().getContentType() != null && ressponse.getEntity().getContentType().getValue() != null) {
        String contentType = ressponse.getEntity().getContentType().getValue();
        if (contentType.contains("charset=")) {
            return contentType.substring(contentType.indexOf("charset=") + 8);
        }
    }
    return null;
}
 
Example 17
Source File: DefaultRequestContentTypeTestCase.java    From product-ei with Apache License 2.0 5 votes vote down vote up
private String getResponse(HttpResponse response) throws Exception {
    StringBuffer buffer = new StringBuffer();

    if (response.getEntity() != null) {
        InputStream in = response.getEntity().getContent();
        int length;
        byte[] tmp = new byte[2048];
        while ((length = in.read(tmp)) != -1) {
            buffer.append(new String(tmp, 0, length));
        }
    }
    return buffer.toString();
}
 
Example 18
Source File: APIImportConfigAdapter.java    From apimanager-swagger-promote with Apache License 2.0 5 votes vote down vote up
private InputStream getAPIDefinitionFromURL(String urlToAPIDefinition) throws AppException {
	URLParser url = new URLParser(urlToAPIDefinition);
	String uri = url.getUri();
	String username = url.getUsername();
	String password = url.getPassword();
	CloseableHttpClient httpclient = createHttpClient(uri, username, password);
	try {
		RequestConfig config = RequestConfig.custom()
				.setRelativeRedirectsAllowed(true)
				.setCircularRedirectsAllowed(true)
				.build();
		HttpGet httpGet = new HttpGet(uri);
		httpGet.setConfig(config);
		
           ResponseHandler<String> responseHandler = new ResponseHandler<String>() {

               @Override
               public String handleResponse(
                       final HttpResponse response) throws ClientProtocolException, IOException {
                   int status = response.getStatusLine().getStatusCode();
                   if (status >= 200 && status < 300) {
                       HttpEntity entity = response.getEntity();
                       return entity != null ? EntityUtils.toString(entity,StandardCharsets.UTF_8) : null;
                   } else {
                       throw new ClientProtocolException("Unexpected response status: " + status);
                   }
               }

           };
           String responseBody = httpclient.execute(httpGet, responseHandler);
           return new ByteArrayInputStream(responseBody.getBytes(StandardCharsets.UTF_8));
	} catch (Exception e) {
		throw new AppException("Cannot load API-Definition from URI: "+uri, ErrorCode.CANT_READ_API_DEFINITION_FILE, e);
	} finally {
		try {
			httpclient.close();
		} catch (Exception ignore) {}
	}
}
 
Example 19
Source File: Util.java    From product-ei with Apache License 2.0 5 votes vote down vote up
/**
 * Extracts the payload from a HTTP response. For a given HttpResponse object, this method can be called only once.
 *
 * @param response HttpResponse instance to be extracted
 * @return Content payload
 * @throws IOException If an error occurs while reading from the response
 */
public static String getResponsePayload(HttpResponse response) throws IOException {
    String responseAsString = "";
    if (response.getEntity() != null) {
        InputStream in = response.getEntity().getContent();
        int length;
        byte[] tmp = new byte[2048];
        StringBuilder buffer = new StringBuilder();
        while ((length = in.read(tmp)) != -1) {
            buffer.append(new String(tmp, 0, length));
        }
        responseAsString = buffer.toString();
    }
    return responseAsString;
}
 
Example 20
Source File: CbApi.java    From PressureNet-SDK with MIT License 4 votes vote down vote up
@Override
protected String doInBackground(String... params) {
	String responseText = "";
	try {
		DefaultHttpClient client = new DefaultHttpClient();
		List<NameValuePair> nvps = new ArrayList<NameValuePair>();
		nvps.add(new BasicNameValuePair("min_latitude", apiCall
				.getMinLat() + "" + ""));
		nvps.add(new BasicNameValuePair("max_latitude", apiCall
				.getMaxLat() + "" + ""));
		nvps.add(new BasicNameValuePair("min_longitude", apiCall
				.getMinLon() + "" + ""));
		nvps.add(new BasicNameValuePair("max_longitude", apiCall
				.getMaxLon() + "" + ""));
		
		nvps.add(new BasicNameValuePair("api_key", apiCall.getApiKey()));
		nvps.add(new BasicNameValuePair("format", apiCall.getFormat()));
		nvps.add(new BasicNameValuePair("limit", apiCall.getLimit()
				+ ""));
		nvps.add(new BasicNameValuePair("global", apiCall.isGlobal()
				+ ""));
		nvps.add(new BasicNameValuePair("since_last_call", apiCall
				.isSinceLastCall() + ""));
		nvps.add(new BasicNameValuePair("sdk_version", CbConfiguration.SDK_VERSION));
		nvps.add(new BasicNameValuePair("source", "pressurenet"));

		

		String serverURL = apiServerURL;

		if (params[0].equals("Readings")) {
			serverURL = apiServerURL;
			nvps.add(new BasicNameValuePair("start_time", apiCall
					.getStartTime() + ""));
			nvps.add(new BasicNameValuePair("end_time", apiCall
					.getEndTime() + ""));
		} else {
			serverURL = apiConditionsServerURL;
			nvps.add(new BasicNameValuePair("start_time", (apiCall
					.getStartTime() / 1000 )+ ""));
			nvps.add(new BasicNameValuePair("end_time",(apiCall
					.getEndTime() / 1000 )+ ""));
		}
		
		String paramString = URLEncodedUtils.format(nvps, "utf-8");

		serverURL = serverURL + paramString;
		apiCall.setCallURL(serverURL);
		log("cbservice api sending " + serverURL);
		HttpGet get = new HttpGet(serverURL);
		// Execute the GET call and obtain the response
		HttpResponse getResponse = client.execute(get);
		HttpEntity responseEntity = getResponse.getEntity()	;
		log("response " + responseEntity.getContentLength());

		BufferedReader r = new BufferedReader(new InputStreamReader(
				responseEntity.getContent()));

		StringBuilder total = new StringBuilder();
		String line;
		if (r != null) {
			while ((line = r.readLine()) != null) {
				total.append(line);
			}
			responseText = total.toString();
		}
	} catch (Exception e) {
		// System.out.println("api error");
		//e.printStackTrace();
	}
	log(responseText);
	
	resultText = responseText;

	// handler.postDelayed(jsonProcessor, 0);
	SaveAPIData save = new SaveAPIData();
	save.execute("");
	return responseText;
}