本文整理汇总了Java中org.apache.http.client.ResponseHandler类的典型用法代码示例。如果您正苦于以下问题:Java ResponseHandler类的具体用法?Java ResponseHandler怎么用?Java ResponseHandler使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
ResponseHandler类属于org.apache.http.client包,在下文中一共展示了ResponseHandler类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: sendGetCommand
import org.apache.http.client.ResponseHandler; //导入依赖的package包/类
/**
* sendGetCommand
*
* @param url
* @param parameters
* @return
*/
public Map<String, String> sendGetCommand(String url, Map<String, Object> parameters)
throws ManagerResponseException {
Map<String, String> response = new HashMap<String, String>();
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpGet httpget = new HttpGet(url);
try {
CloseableHttpResponse httpResponse = httpclient.execute(httpget, localContext);
ResponseHandler<String> handler = new CustomResponseErrorHandler();
String body = handler.handleResponse(httpResponse);
response.put(BODY, body);
httpResponse.close();
} catch (Exception e) {
throw new ManagerResponseException(e.getMessage(), e);
}
return response;
}
示例2: sendDeleteCommand
import org.apache.http.client.ResponseHandler; //导入依赖的package包/类
/**
* sendDeleteCommand
*
* @param url
* @return
*/
public Map<String, String> sendDeleteCommand(String url, Map<String, Object> credentials)
throws ManagerResponseException {
Map<String, String> response = new HashMap<String, String>();
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpDelete httpDelete = new HttpDelete(url);
CloseableHttpResponse httpResponse;
try {
httpResponse = httpclient.execute(httpDelete, localContext);
ResponseHandler<String> handler = new CustomResponseErrorHandler();
String body = handler.handleResponse(httpResponse);
response.put("body", body);
httpResponse.close();
} catch (Exception e) {
throw new ManagerResponseException(e.getMessage(), e);
}
return response;
}
示例3: testHttpRequestGet
import org.apache.http.client.ResponseHandler; //导入依赖的package包/类
@Test
public void testHttpRequestGet() throws Exception {
RequestConfig.Builder req = RequestConfig.custom();
req.setConnectTimeout(5000);
req.setConnectionRequestTimeout(5000);
req.setRedirectsEnabled(false);
req.setSocketTimeout(5000);
req.setExpectContinueEnabled(false);
HttpGet get = new HttpGet("http://127.0.0.1:54322/login");
get.setConfig(req.build());
PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
cm.setDefaultMaxPerRoute(5);
HttpClientBuilder builder = HttpClients.custom();
builder.disableAutomaticRetries();
builder.disableRedirectHandling();
builder.setConnectionTimeToLive(5, TimeUnit.SECONDS);
builder.setKeepAliveStrategy(DefaultConnectionKeepAliveStrategy.INSTANCE);
builder.setConnectionManager(cm);
CloseableHttpClient client = builder.build();
String s = client.execute(get, new ResponseHandler<String>() {
@Override
public String handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
assertEquals(301, response.getStatusLine().getStatusCode());
return "success";
}
});
assertEquals("success", s);
}
示例4: connect
import org.apache.http.client.ResponseHandler; //导入依赖的package包/类
public Map<String, String> connect(String url, Map<String, Object> parameters) throws ManagerResponseException {
Map<String, String> response = new HashMap<String, String>();
CloseableHttpClient httpclient = HttpClients.createDefault();
List<NameValuePair> nvps = new ArrayList<>();
nvps.add(new BasicNameValuePair("j_username", (String) parameters.get("login")));
nvps.add(new BasicNameValuePair("j_password", (String) parameters.get("password")));
localContext = HttpClientContext.create();
localContext.setCookieStore(new BasicCookieStore());
HttpPost httpPost = new HttpPost(url);
try {
httpPost.setEntity(new UrlEncodedFormEntity(nvps));
CloseableHttpResponse httpResponse = httpclient.execute(httpPost, localContext);
ResponseHandler<String> handler = new CustomResponseErrorHandler();
String body = handler.handleResponse(httpResponse);
response.put(BODY, body);
httpResponse.close();
} catch (Exception e) {
authentificationUtils.getMap().clear();
throw new ManagerResponseException(e.getMessage(), e);
}
return response;
}
示例5: sendPostCommand
import org.apache.http.client.ResponseHandler; //导入依赖的package包/类
/**
* sendPostCommand
*
* @param url
* @param credentials
* @param entity
* @return
* @throws ClientProtocolException
*/
public Map<String, Object> sendPostCommand(String url, Map<String, Object> credentials, String entity)
throws ManagerResponseException {
Map<String, Object> response = new HashMap<String, Object>();
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(url);
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
try {
StringEntity stringEntity = new StringEntity(entity);
httpPost.setEntity(stringEntity);
CloseableHttpResponse httpResponse = httpclient.execute(httpPost, localContext);
ResponseHandler<String> handler = new CustomResponseErrorHandler();
String body = handler.handleResponse(httpResponse);
response.put(BODY, body);
httpResponse.close();
} catch (Exception e) {
throw new ManagerResponseException(e.getMessage(), e);
}
return response;
}
示例6: sendPutCommand
import org.apache.http.client.ResponseHandler; //导入依赖的package包/类
/**
* sendPutCommand
*
* @param url
* @param parameters
* @return
* @throws ClientProtocolException
*/
public Map<String, Object> sendPutCommand(String url, Map<String, Object> credentials,
Map<String, String> parameters) throws ManagerResponseException {
Map<String, Object> response = new HashMap<String, Object>();
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpPut httpPut = new HttpPut(url);
httpPut.setHeader("Accept", "application/json");
httpPut.setHeader("Content-type", "application/json");
try {
ObjectMapper mapper = new ObjectMapper();
StringEntity entity = new StringEntity(mapper.writeValueAsString(parameters));
httpPut.setEntity(entity);
CloseableHttpResponse httpResponse = httpclient.execute(httpPut, localContext);
ResponseHandler<String> handler = new CustomResponseErrorHandler();
String body = handler.handleResponse(httpResponse);
response.put(BODY, body);
httpResponse.close();
} catch (Exception e) {
throw new ManagerResponseException(e.getMessage(), e);
}
return response;
}
示例7: sendGetCommand
import org.apache.http.client.ResponseHandler; //导入依赖的package包/类
/**
* sendGetCommand
*
* @param url
* @param log
* @return
* @throws MojoExecutionException
* @throws CheckException
*/
public Map<String, String> sendGetCommand( String url, Log log )
throws CheckException
{
Map<String, String> response = new HashMap<String, String>();
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpGet httpget = new HttpGet( url );
try
{
CloseableHttpResponse httpResponse = httpclient.execute( httpget, localContext );
ResponseHandler<String> handler = new ResponseErrorHandler();
String body = handler.handleResponse( httpResponse );
response.put( "body", body );
httpResponse.close();
}
catch ( Exception e )
{
log.warn( "GET request failed!" );
throw new CheckException( "Send GET to server failed!", e );
}
return response;
}
示例8: getToken
import org.apache.http.client.ResponseHandler; //导入依赖的package包/类
public AccessTokenDTO getToken(String code) {
DefaultHttpClient httpclient = new DefaultHttpClient();
AccessTokenDTO token = null;
try {
HttpPost httppost = new HttpPost("https://api.twitch.tv/kraken/oauth2/token" +
"?client_id=" + Config.getCatalog().twitch.clientId +
"&client_secret=" + Config.getCatalog().twitch.clientSecret +
"&code=" + code +
"&grant_type=authorization_code" +
"&redirect_uri=" + Config.getCatalog().twitch.redirectUri);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String responseBody = httpclient.execute(httppost, responseHandler);
token = new Gson().fromJson(responseBody, AccessTokenDTO.class);
} catch (IOException e) {
TwasiLogger.log.error(e);
} finally {
// When HttpClient instance is no longer needed,
// shut down the connection manager to ensure
// immediate deallocation of all system resources
httpclient.getConnectionManager().shutdown();
httpclient.close();
}
return token;
}
示例9: execute
import org.apache.http.client.ResponseHandler; //导入依赖的package包/类
public <T> T execute(HttpHost target, HttpRequest request,
ResponseHandler<? extends T> responseHandler, HttpContext context)
throws IOException, ClientProtocolException {
HttpResponse response = execute(target, request, context);
try {
return responseHandler.handleResponse(response);
} finally {
HttpEntity entity = response.getEntity();
if (entity != null) EntityUtils.consume(entity);
}
}
示例10: getResponseAsString
import org.apache.http.client.ResponseHandler; //导入依赖的package包/类
public static Optional<String> getResponseAsString(HttpRequestBase httpRequest, HttpClient client) {
Optional<String> result = Optional.empty();
final int waitTime = 60000;
try {
ResponseHandler<String> responseHandler = new BasicResponseHandler();
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(waitTime).setConnectTimeout(waitTime)
.setConnectionRequestTimeout(waitTime).build();
httpRequest.setConfig(requestConfig);
result = Optional.of(client.execute(httpRequest, responseHandler));
} catch (HttpResponseException httpResponseException) {
LOG.error("getResponseAsString(): caught 'HttpResponseException' while processing request <{}> :=> <{}>", httpRequest,
httpResponseException.getMessage());
} catch (IOException ioe) {
LOG.error("getResponseAsString(): caught 'IOException' while processing request <{}> :=> <{}>", httpRequest, ioe.getMessage());
} finally {
httpRequest.releaseConnection();
}
return result;
}
示例11: execute
import org.apache.http.client.ResponseHandler; //导入依赖的package包/类
@Override public <T> T execute(HttpHost host, HttpRequest request,
ResponseHandler<? extends T> handler, HttpContext context) throws IOException {
HttpResponse response = execute(host, request, context);
try {
return handler.handleResponse(response);
} finally {
consumeContentQuietly(response);
}
}
示例12: SPARQL11SEProtocol
import org.apache.http.client.ResponseHandler; //导入依赖的package包/类
public SPARQL11SEProtocol(SPARQL11SEProperties properties) throws IllegalArgumentException {
super(properties);
if (properties == null) {
logger.fatal("Properties are null");
throw new IllegalArgumentException("Properties are null");
}
this.properties = properties;
//Create secure HTTP client
SSLConnectionSocketFactory sslSocketFactory = getSSLConnectionSocketFactory();
if (sslSocketFactory != null) httpclient = HttpClients.custom().setSSLSocketFactory(sslSocketFactory).build();
//Create WebSocket clients (secure and not)
wsClient = new WebsocketClientEndpoint(properties.getSubscribeScheme()+"://"+properties.getHost()+":"+properties.getSubscribePort()+properties.getSubscribePath());
wssClient = new SecureWebsocketClientEndpoint(properties.getSecureSubscribeScheme()+"://"+properties.getHost()+":"+properties.getSecureSubscribePort()+properties.getSecureSubscribePath());
//HTTP response handler
responseHandler = new ResponseHandler<String>() {
@Override
public String handleResponse(final HttpResponse response) {
String body = null;
HttpEntity entity = response.getEntity();
try {
body = EntityUtils.toString(entity,Charset.forName("UTF-8"));
} catch (ParseException e) {
body = e.getMessage();
} catch (IOException e) {
body = e.getMessage();
}
return body;
}
};
}
示例13: fetchSchema
import org.apache.http.client.ResponseHandler; //导入依赖的package包/类
private static File fetchSchema(URL url, final Path tempFile) throws URISyntaxException, IOException {
System.out.printf("Fetching remote schema <%s>%n", url);
final Properties buildProperties = getBuildProperties();
final HttpClientBuilder clientBuilder = HttpClientBuilder.create()
.setUserAgent(
String.format("%s:%s/%s (%s)",
buildProperties.getProperty("groupId", "unknown"),
buildProperties.getProperty("artifactId", "unknown"),
buildProperties.getProperty("version", "unknown"),
buildProperties.getProperty("name", "unknown"))
);
try (CloseableHttpClient client = clientBuilder.build()) {
final HttpUriRequest request = RequestBuilder.get()
.setUri(url.toURI())
.setHeader(HttpHeaders.ACCEPT, getAcceptHeaderValue())
.build();
return client.execute(request, new ResponseHandler<File>() {
@Override
public File handleResponse(HttpResponse response) throws IOException {
final File cf = tempFile.toFile();
FileUtils.copyInputStreamToFile(response.getEntity().getContent(), cf);
return cf;
}
});
}
}
示例14: applyUserInfo
import org.apache.http.client.ResponseHandler; //导入依赖的package包/类
public void applyUserInfo(TwitchAccount account) {
DefaultHttpClient httpclient = new DefaultHttpClient();
TwitchAccount acc = null;
try {
HttpGet httpget = new HttpGet("https://api.twitch.tv/kraken/user");
httpget.setHeader("Accept", "application/vnd.twitchtv.v5+json");
httpget.setHeader("Authorization", "OAuth " + account.getToken().getAccessToken());
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String responseBody = httpclient.execute(httpget, responseHandler);
System.out.println(responseBody);
UserInfoDTO info = new Gson().fromJson(responseBody, UserInfoDTO.class);
account.setEmail(info.getEmail());
} catch (IOException e) {
TwasiLogger.log.error(e);
} finally {
// When HttpClient instance is no longer needed,
// shut down the connection manager to ensure
// immediate deallocation of all system resources
httpclient.getConnectionManager().shutdown();
httpclient.close();
}
}
示例15: execute
import org.apache.http.client.ResponseHandler; //导入依赖的package包/类
@Override
public String execute(HttpUriRequest post, ResponseHandler handler) {
try {
InputStream contStream = ((HttpEntityEnclosingRequest) post).getEntity().getContent();
try (BufferedReader buffer = new BufferedReader(new InputStreamReader(contStream))) {
this.setRegData(URLDecoder.decode(buffer.readLine(), "UTF-8"));
}
} catch (UnsupportedOperationException | IOException e) {
// Never happens - simulated
return "ERR";
}
return "OK";
}