下面列出了怎么用org.apache.http.impl.client.BasicResponseHandler的API类实例代码及写法,或者点击链接到github查看源代码。
protected void httpClientWebData() {
DefaultHttpClient httpClinet = new DefaultHttpClient();
String pediyUrl = ped.getText().toString();
HttpGet httpGet = new HttpGet(pediyUrl);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
try {
String content = httpClinet.execute(httpGet, responseHandler);
mHandler.obtainMessage(MSG_SUCCESS, content).sendToTarget();
} catch (IOException e) {
e.printStackTrace();
}
}
private String getText(String redirectLocation) {
HttpGet httpget = new HttpGet(redirectLocation);
// Create a response handler
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String responseBody = "";
try {
responseBody = httpclient.execute(httpget, responseHandler);
} catch (Exception e) {
e.printStackTrace();
responseBody = null;
} finally {
httpget.abort();
httpclient.getConnectionManager().shutdown();
}
return responseBody;
}
public void testHttpProxy() throws IOException {
Settings.setLoggingLevel("org.apache.http.wire", Level.DEBUG);
Settings.setLoggingLevel("org.apache.http", Level.DEBUG);
String proxyHost = Settings.getProperty("davmail.proxyHost");
int proxyPort = Settings.getIntProperty("davmail.proxyPort");
HttpHost proxy = new HttpHost(proxyHost, proxyPort);
HttpClientBuilder clientBuilder = HttpClientBuilder.create();
clientBuilder.setProxy(proxy).setUserAgent(DavGatewayHttpClientFacade.IE_USER_AGENT);
clientBuilder.setDefaultCredentialsProvider(getProxyCredentialProvider());
try (CloseableHttpClient httpClient = clientBuilder.build()) {
HttpGet httpget = new HttpGet("http://davmail.sourceforge.net/version.txt");
try (CloseableHttpResponse response = httpClient.execute(httpget)) {
String responseString = new BasicResponseHandler().handleResponse(response);
System.out.println(responseString);
}
}
}
public static String post(String url, String fileName, String json) {
Try<String> uploadedFile = Try.of(() -> {
HttpClient client = HttpClientBuilder.create().build();
HttpEntity entity = MultipartEntityBuilder
.create()
.setCharset(UTF_8)
.setMode(BROWSER_COMPATIBLE)
.addBinaryBody("file", json.getBytes(UTF_8), ContentType.create(ContentType.TEXT_PLAIN.getMimeType(), UTF_8), fileName)
.build();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(entity);
HttpResponse response = client.execute(httpPost);
return new BasicResponseHandler().handleResponse(response);
}).onFailure(t -> logger.error("[POST json]", t));
return (uploadedFile.isSuccess()) ? uploadedFile.get() : null;
}
public static String post(String url, String fileName, BufferedImage image) {
Try<String> uploadedFile = Try.of(() -> {
HttpClient client = HttpClientBuilder.create().build();
HttpEntity entity = MultipartEntityBuilder
.create()
.setCharset(UTF_8)
.setMode(BROWSER_COMPATIBLE)
.addBinaryBody("file", getImageBytes(image), DEFAULT_BINARY, fileName)
.build();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(entity);
HttpResponse response = client.execute(httpPost);
return new BasicResponseHandler().handleResponse(response);
}).onFailure(t -> logger.error("[POST image]", t));
return (uploadedFile.isSuccess()) ? uploadedFile.get() : null;
}
public String notifyHunter(byte[] content) throws IOException {
try {
String request = new String(content);
SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, (certificate, authType) -> true).build();
HttpClient httpclient = HttpClients.custom().setSSLContext(sslContext).setSSLHostnameVerifier(new NoopHostnameVerifier()).build();
HttpPost httpPost = new HttpPost("https://api"+hunterDomain.substring(hunterDomain.indexOf("."))+"/api/record_injection");
String json = "{\"request\": \""+request.replace("\\", "\\\\").replace("\"", "\\\"").replace("\r\n", "\\n")+"\", \"owner_correlation_key\": \""+hunterKey+"\", \"injection_key\": \""+injectKey+"\"}";
StringEntity entity = new StringEntity(json);
entity.setContentType("applicaiton/json");
httpPost.setEntity(entity);
HttpResponse response = httpclient.execute(httpPost);
String responseString = new BasicResponseHandler().handleResponse(response);
return responseString;
} catch (NoSuchAlgorithmException | KeyStoreException | KeyManagementException ex) {
Logger.getLogger(HunterRequest.class.getName()).log(Level.SEVERE, null, ex);
}
return "Error Notifying Probe Server!";
}
public static String getText(String redirectLocation) {
HttpGet httpget = new HttpGet(redirectLocation);
// Create a response handler
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String responseBody = "";
try {
responseBody = httpclient.execute(httpget, responseHandler);
} catch (Exception e) {
e.printStackTrace();
responseBody = null;
} finally {
httpget.abort();
// httpclient.getConnectionManager().shutdown();
}
return responseBody;
}
/**
* Send HTTP GET request to {@link #endpointUrl}, updates {@link #csrfToken}
* token
*
* @return true if {@link #endpointUrl} is accessible
* @throws IOException
* @throws ClientProtocolException
* @throws AuthenticationException
*/
protected void fetchCsrfTokenFromHac() throws ClientProtocolException, IOException, AuthenticationException {
final HttpGet getRequest = new HttpGet(getEndpointUrl());
try {
final HttpResponse response = httpClient.execute(getRequest, getContext());
final String responseString = new BasicResponseHandler().handleResponse(response);
csrfToken = getCsrfToken(responseString);
if (StringUtil.isBlank(csrfToken)) {
throw new AuthenticationException(ErrorMessage.CSRF_TOKEN_CANNOT_BE_OBTAINED);
}
} catch (UnknownHostException error) {
final String errorMessage = error.getMessage();
final Matcher matcher = HACPreferenceConstants.HOST_REGEXP_PATTERN.matcher(getEndpointUrl());
if (matcher.find() && matcher.group(1).equals(errorMessage)) {
throw new UnknownHostException(
String.format(ErrorMessage.UNKNOWN_HOST_EXCEPTION_MESSAGE_FORMAT, matcher.group(1)));
}
throw error;
}
}
public static RateLimitsDto generateRateLimits(String apiKey, String opsGenieHost) throws IOException {
try {
HttpClient client = HttpClientBuilder.create().build();
HttpGet httpGet = new HttpGet(opsGenieHost + "/v2/request-limits/");
httpGet.addHeader(HttpHeaders.AUTHORIZATION, "GenieKey " + apiKey);
String body = client.execute(httpGet, new BasicResponseHandler());
DataDto result = new DataDto();
BackupUtils.fromJson(result, body);
return result.getData();
} catch (Exception e) {
logger.error("Could not initiate rate limits. " + e.getMessage());
System.exit(1);
return null;
}
}
private Snapshot retrieveMetrics(ConsumerId consumer) {
String metricsUri = node.metricsUri(consumer).toString();
log.log(FINE, () -> "Retrieving metrics from host " + metricsUri);
try {
String metricsJson = httpClient.execute(new HttpGet(metricsUri), new BasicResponseHandler());
var metricsBuilders = GenericJsonUtil.toMetricsPackets(metricsJson);
var metrics = processAndBuild(metricsBuilders,
new ServiceIdDimensionProcessor(),
new ClusterIdDimensionProcessor(),
new PublicDimensionsProcessor(MAX_DIMENSIONS));
snapshotsRetrieved ++;
log.log(FINE, () -> "Successfully retrieved " + metrics.size() + " metrics packets from " + metricsUri);
return new Snapshot(Instant.now(clock), metrics);
} catch (IOException e) {
log.warning("Unable to retrieve metrics from " + metricsUri + ": " + Exceptions.toMessageString(e));
return new Snapshot(Instant.now(clock), emptyList());
}
}
static <T extends SparkResponse> T executeHttpMethodAndGetResponse(HttpClient client, HttpRequestBase httpRequest, Class<T> responseClass) throws FailedSparkRequestException {
T response;
try {
final String stringResponse = client.execute(httpRequest, new BasicResponseHandler());
if (stringResponse != null) {
response = MapperWrapper.MAPPER.readValue(stringResponse, responseClass);
} else {
throw new FailedSparkRequestException("Received empty string response");
}
} catch (IOException e) {
throw new FailedSparkRequestException(e);
} finally {
httpRequest.releaseConnection();
}
if (response == null) {
throw new FailedSparkRequestException("An issue occured with the cluster's response.");
}
return response;
}
@SuppressWarnings({"rawtypes", "unchecked"})
private void postDeviceStatus(String baseURL, DefaultHttpClient httpclient) throws Exception {
String devicestatusURL = baseURL + "devicestatus";
Log.i(TAG, "devicestatusURL: " + devicestatusURL);
JSONObject json = new JSONObject();
json.put("uploaderBattery", DexcomG4Activity.batLevel);
String jsonString = json.toString();
HttpPost post = new HttpPost(devicestatusURL);
StringEntity se = new StringEntity(jsonString);
post.setEntity(se);
post.setHeader("Accept", "application/json");
post.setHeader("Content-type", "application/json");
ResponseHandler responseHandler = new BasicResponseHandler();
httpclient.execute(post, responseHandler);
}
@Test
@SuppressWarnings("unchecked")
public void shouldAttachTraceIdWhenCallingAnotherServiceForHttpClient()
throws Exception {
Span span = this.tracer.nextSpan().name("foo").start();
try (Tracer.SpanInScope ws = this.tracer.withSpanInScope(span)) {
String response = this.httpClientBuilder.build().execute(
new HttpGet("http://localhost:" + this.port),
new BasicResponseHandler());
then(response).isNotEmpty();
}
then(this.tracer.currentSpan()).isNull();
then(this.spans).isNotEmpty().extracting("traceId", String.class)
.containsOnly(span.context().traceIdString());
then(this.spans).extracting("kind.name").contains("CLIENT");
}
public static String[] getHosts() {
try {
DefaultHttpClient client = new DefaultHttpClient();
client.getCredentialsProvider().setCredentials(new AuthScope(host_name, getAdminPort()),
new UsernamePasswordCredentials("admin", "admin"));
HttpGet get = new HttpGet("http://" + host_name + ":" + admin_port + "/manage/v2/hosts?format=json");
HttpResponse response = client.execute(get);
ResponseHandler<String> handler = new BasicResponseHandler();
String body = handler.handleResponse(response);
JsonNode actualObj = new ObjectMapper().readTree(body);
JsonNode nameNode = actualObj.path("host-default-list").path("list-items");
List<String> hosts = nameNode.findValuesAsText("nameref");
String[] s = new String[hosts.size()];
hosts.toArray(s);
return s;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
private boolean isRunning(String host) {
try {
DefaultHttpClient client = new DefaultHttpClient();
client.getCredentialsProvider().setCredentials(new AuthScope(host, 7997),
new UsernamePasswordCredentials("admin", "admin"));
HttpGet get = new HttpGet("http://" + host + ":7997?format=json");
HttpResponse response = client.execute(get);
ResponseHandler<String> handler = new BasicResponseHandler();
String body = handler.handleResponse(response);
if (body.contains("Healthy")) {
return true;
}
} catch (Exception e) {
return false;
}
return false;
}
private boolean isRunning(String host) {
try {
DefaultHttpClient client = new DefaultHttpClient();
client.getCredentialsProvider().setCredentials(new AuthScope(host, 7997),
new UsernamePasswordCredentials("admin", "admin"));
HttpGet get = new HttpGet("http://" + host + ":7997?format=json");
HttpResponse response = client.execute(get);
ResponseHandler<String> handler = new BasicResponseHandler();
String body = handler.handleResponse(response);
if (body.toLowerCase().contains("healthy")) {
return true;
} else {
return false;
}
} catch (Exception e) {
return false;
}
}
@Override
public List<EarthQuakeRec> handleResponse(HttpResponse response)
throws ClientProtocolException, IOException {
List<EarthQuakeRec> result = new ArrayList<EarthQuakeRec>();
String JSONResponse = new BasicResponseHandler()
.handleResponse(response);
try {
JSONObject object = (JSONObject) new JSONTokener(JSONResponse)
.nextValue();
JSONArray earthquakes = object.getJSONArray("earthquakes");
for (int i = 0; i < earthquakes.length(); i++) {
JSONObject tmp = (JSONObject) earthquakes.get(i);
result.add(new EarthQuakeRec(
tmp.getDouble("lat"),
tmp.getDouble("lng"),
tmp.getDouble("magnitude")));
}
} catch (JSONException e) {
e.printStackTrace();
}
return result;
}
private void postDeviceStatus(String baseURL, Header apiSecretHeader, DefaultHttpClient httpclient) throws Exception {
String devicestatusURL = baseURL + "devicestatus";
Log.i(TAG, "devicestatusURL: " + devicestatusURL);
JSONObject json = new JSONObject();
json.put("uploaderBattery", getBatteryLevel());
String jsonString = json.toString();
HttpPost post = new HttpPost(devicestatusURL);
if (apiSecretHeader != null) {
post.setHeader(apiSecretHeader);
}
StringEntity se = new StringEntity(jsonString);
post.setEntity(se);
post.setHeader("Accept", "application/json");
post.setHeader("Content-type", "application/json");
ResponseHandler responseHandler = new BasicResponseHandler();
httpclient.execute(post, responseHandler);
}
@Test
public void createNetworkTest() throws Exception {
String networkName = "example network 1";
String tenant_net_uuid = UUID.randomUUID().toString();
SspClient sspClient = spy(new SspClient(apiUrl, username, password));
HttpClient client = mock(HttpClient.class);
doReturn(client).when(sspClient).getHttpClient();
String body = "{\"uuid\":\"" + tenant_net_uuid + "\",\"name\":\"" + networkName
+ "\",\"tenant_uuid\":\"" + uuid + "\"}";
when(client.execute(any(HttpUriRequest.class), any(BasicResponseHandler.class))).thenReturn(body);
SspClient.TenantNetwork tnet = sspClient.createTenantNetwork(uuid, networkName);
assertEquals(tnet.name, networkName);
assertEquals(tnet.uuid, tenant_net_uuid);
assertEquals(tnet.tenantUuid, uuid);
}
/**
* @return the RAW XML document of ItemLookup (Large Response) from Amazon
* product advertisement API
* @throws InvalidKeyException
* @throws NoSuchAlgorithmException
* @throws ClientProtocolException
* @throws IOException
*/
public String getXMLLargeResponse() throws InvalidKeyException,
NoSuchAlgorithmException, ClientProtocolException, IOException {
String responseBody = "";
String signedurl = signInput();
try {
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet(signedurl);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
responseBody = httpclient.execute(httpget, responseHandler);
// responseBody now contains the contents of the page
// System.out.println(responseBody);
httpclient.getConnectionManager().shutdown();
} catch (Exception e) {
System.out.println("Exception" + " " + itemID + " " + e.getClass());
}
return responseBody;
}
private String executeGetRequest(String url) throws IOException {
RequestConfig requestConfig = RequestConfig.custom()
.setConnectTimeout(15000)
.setSocketTimeout(15000)
.build();
HttpGet method = new HttpGet(url);
method.setConfig(requestConfig);
try (CloseableHttpClient client = HttpClients.createDefault()) {
ResponseHandler<String> responseHandler = new BasicResponseHandler();
return client.execute(method, responseHandler);
}
}
private String[] executeRequest(HttpUriRequest request) throws ClientProtocolException, IOException {
try (CloseableHttpClient client = HttpClients.createDefault()) {
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String response = client.execute(request, responseHandler);
return response.split("\\r?\\n");
}
}
private String executeRequest(HttpUriRequest request) throws IOException {
try (CloseableHttpClient client = HttpClients.createDefault()) {
ResponseHandler<String> responseHandler = new BasicResponseHandler();
return client.execute(request, responseHandler);
}
}
@Override
public String getAccessToken(boolean forceRefresh) throws WxErrorException {
if (this.configStorage.isAccessTokenExpired() || forceRefresh) {
synchronized (this.globalAccessTokenRefreshLock) {
if (this.configStorage.isAccessTokenExpired()) {
String url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?"
+ "&corpid=" + this.configStorage.getCorpId()
+ "&corpsecret=" + this.configStorage.getCorpSecret();
try {
HttpGet httpGet = new HttpGet(url);
if (this.httpProxy != null) {
RequestConfig config = RequestConfig.custom()
.setProxy(this.httpProxy).build();
httpGet.setConfig(config);
}
String resultContent = null;
try (CloseableHttpClient httpclient = getRequestHttpClient();
CloseableHttpResponse response = httpclient.execute(httpGet)) {
resultContent = new BasicResponseHandler().handleResponse(response);
} finally {
httpGet.releaseConnection();
}
WxError error = WxError.fromJson(resultContent, WxType.CP);
if (error.getErrorCode() != 0) {
throw new WxErrorException(error);
}
WxAccessToken accessToken = WxAccessToken.fromJson(resultContent);
this.configStorage.updateAccessToken(
accessToken.getAccessToken(), accessToken.getExpiresIn());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
}
return this.configStorage.getAccessToken();
}
@Override
public String getAccessToken(boolean forceRefresh) throws WxErrorException {
Lock lock = this.getWxMpConfigStorage().getAccessTokenLock();
try {
lock.lock();
if (this.getWxMpConfigStorage().isAccessTokenExpired() || forceRefresh) {
String url = String.format(WxMpService.GET_ACCESS_TOKEN_URL,
this.getWxMpConfigStorage().getAppId(), this.getWxMpConfigStorage().getSecret());
try {
HttpGet httpGet = new HttpGet(url);
if (this.getRequestHttpProxy() != null) {
RequestConfig config = RequestConfig.custom().setProxy(this.getRequestHttpProxy()).build();
httpGet.setConfig(config);
}
try (CloseableHttpResponse response = getRequestHttpClient().execute(httpGet)) {
String resultContent = new BasicResponseHandler().handleResponse(response);
WxError error = WxError.fromJson(resultContent, WxType.MP);
if (error.getErrorCode() != 0) {
throw new WxErrorException(error);
}
WxAccessToken accessToken = WxAccessToken.fromJson(resultContent);
this.getWxMpConfigStorage().updateAccessToken(accessToken.getAccessToken(),
accessToken.getExpiresIn());
} finally {
httpGet.releaseConnection();
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
} finally {
lock.unlock();
}
return this.getWxMpConfigStorage().getAccessToken();
}
@Override
public String getAccessToken(boolean forceRefresh) throws WxErrorException {
Lock lock = this.getWxMaConfig().getAccessTokenLock();
try {
lock.lock();
if (this.getWxMaConfig().isAccessTokenExpired() || forceRefresh) {
String url = String.format(WxMaService.GET_ACCESS_TOKEN_URL, this.getWxMaConfig().getAppid(),
this.getWxMaConfig().getSecret());
try {
HttpGet httpGet = new HttpGet(url);
if (this.getRequestHttpProxy() != null) {
RequestConfig config = RequestConfig.custom().setProxy(this.getRequestHttpProxy()).build();
httpGet.setConfig(config);
}
try (CloseableHttpResponse response = getRequestHttpClient().execute(httpGet)) {
String resultContent = new BasicResponseHandler().handleResponse(response);
WxError error = WxError.fromJson(resultContent);
if (error.getErrorCode() != 0) {
throw new WxErrorException(error);
}
WxAccessToken accessToken = WxAccessToken.fromJson(resultContent);
this.getWxMaConfig().updateAccessToken(accessToken.getAccessToken(),
accessToken.getExpiresIn());
} finally {
httpGet.releaseConnection();
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
} finally {
lock.unlock();
}
return this.getWxMaConfig().getAccessToken();
}
/**
* This response as a string.
* @return String representation of this {@link Response}.
*/
@Override
public String toString() {
final String CRLF = "" + (char) 0x0D + (char) 0x0A;
try {
final StringBuilder builder = new StringBuilder()
.append(this.backbone.getStatusLine().toString())
.append(CRLF)
.append(
Stream.of(
this.backbone.getAllHeaders()
).map(header -> header.toString())
.collect(Collectors.joining(CRLF))
)
.append(CRLF).append(CRLF)
.append(
new BasicResponseHandler().handleEntity(
this.backbone.getEntity()
)
);
return builder.toString();
} catch (final IOException ex) {
throw new IllegalStateException(
"IOException when reading the HTTP response. " + ex
);
}
}
@Override
protected String getFreeBusyData(String attendee, String start, String end, int interval) throws IOException {
String freebusyUrl = publicFolderUrl + "/?cmd=freebusy" +
"&start=" + start +
"&end=" + end +
"&interval=" + interval +
"&u=SMTP:" + attendee;
HttpGet httpGet = new HttpGet(freebusyUrl);
httpGet.setHeader("Content-Type", "text/xml");
String fbdata;
try (CloseableHttpResponse response = httpClientAdapter.execute(httpGet)) {
fbdata = StringUtil.getLastToken(new BasicResponseHandler().handleResponse(response), "<a:fbdata>", "</a:fbdata>");
}
return fbdata;
}
@Override
public String handleResponse(HttpResponse response) throws IOException {
this.response = response;
if (HttpClientAdapter.isRedirect(response)) {
return null;
} else {
responseBodyAsString = new BasicResponseHandler().handleResponse(response);
return responseBodyAsString;
}
}
/**
* Handle request response and return response as string.
* response body is null on redirect
*
* @param response response object
* @return response body as string
* @throws IOException on error
*/
@Override
public String handleResponse(HttpResponse response) throws IOException {
this.response = response;
if (HttpClientAdapter.isRedirect(response)) {
return null;
} else {
responseBodyAsString = new BasicResponseHandler().handleResponse(response);
return responseBodyAsString;
}
}