本文整理汇总了Java中org.apache.http.HttpException类的典型用法代码示例。如果您正苦于以下问题:Java HttpException类的具体用法?Java HttpException怎么用?Java HttpException使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
HttpException类属于org.apache.http包,在下文中一共展示了HttpException类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: handle
import org.apache.http.HttpException; //导入依赖的package包/类
@Override
public void handle(HttpRequest request, HttpResponse response, HttpContext context) throws HttpException, IOException {
RequestLine line = request.getRequestLine();
Uri uri = Uri.parse(line.getUri());
DatabaseDataEntity entity;
if (uri != null) {
String database = uri.getQueryParameter("database");
String tableName = uri.getQueryParameter("table");
entity = getDataResponse(database, tableName);
if (entity != null) {
response.setStatusCode(200);
response.setEntity(new StringEntity(ParserJson.getSafeJsonStr(entity), "utf-8"));
return;
}
}
entity = new DatabaseDataEntity();
entity.setDataList(new ArrayList<Map<String, String>>());
entity.setCode(BaseEntity.FAILURE_CODE);
response.setStatusCode(200);
response.setEntity(new StringEntity(ParserJson.getSafeJsonStr(entity), "utf-8"));
}
示例2: process
import org.apache.http.HttpException; //导入依赖的package包/类
public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException {
AuthState authState = (AuthState) context.getAttribute(HttpClientContext.TARGET_AUTH_STATE);
if (authState.getAuthScheme() != null || authState.hasAuthOptions()) {
return;
}
// If no authState has been established and this is a PUT or POST request, add preemptive authorisation
String requestMethod = request.getRequestLine().getMethod();
if (alwaysSendAuth || requestMethod.equals(HttpPut.METHOD_NAME) || requestMethod.equals(HttpPost.METHOD_NAME)) {
CredentialsProvider credentialsProvider = (CredentialsProvider) context.getAttribute(HttpClientContext.CREDS_PROVIDER);
HttpHost targetHost = (HttpHost) context.getAttribute(HttpCoreContext.HTTP_TARGET_HOST);
Credentials credentials = credentialsProvider.getCredentials(new AuthScope(targetHost.getHostName(), targetHost.getPort()));
if (credentials == null) {
throw new HttpException("No credentials for preemptive authentication");
}
authState.update(authScheme, credentials);
}
}
示例3: interruptibleGetRange
import org.apache.http.HttpException; //导入依赖的package包/类
/**
* Gets a part of the given URL, writes the content into the given channel.
* Fails if the returned HTTP status is not "206 partial content".
*
* @param <IWC> a generic type for any class that implements InterruptibleChannel and WritableByteChannel
* @param url to get
* @param output written with the content of the HTTP response
* @param etag value of the If-Range header
* @param range_start range byte start (inclusive)
* @param range_end range byte end (inclusive)
*
* @return a response (contains the HTTP Headers, the status code, ...)
*
* @throws IOException IO error
* @throws InterruptedException interrupted
* @throws RuntimeException containing the actual exception if it is not an instance of IOException
*/
public <IWC extends InterruptibleChannel & WritableByteChannel>
HttpResponse interruptibleGetRange(String url, final IWC output, String etag, long range_start, long range_end)
throws IOException, InterruptedException
{
HttpGet get = new HttpGet(url);
get.setHeader("If-Range", etag);
get.setHeader("Range", String.format("bytes=%d-%d", range_start, range_end));
// This validator throws an IOException if the response code is not 206 partial content
ResponseValidator val = new ResponseValidator()
{
@Override
public void validate(HttpResponse response) throws HttpException, IOException
{
if (response.getStatusLine().getStatusCode() != HttpStatus.SC_PARTIAL_CONTENT)
{
throw new IOException("Range request does not return partial content");
}
}
};
return interruptibleRequest(get, output, val);
}
示例4: start
import org.apache.http.HttpException; //导入依赖的package包/类
/**
* Starts the HTTP server.
*
* @return the listening port.
*/
static int start () throws IOException
{
server = ServerBootstrap.bootstrap ().registerHandler ("*",
new HttpRequestHandler ()
{
@Override
public void handle (HttpRequest request, HttpResponse response,
HttpContext context)
throws HttpException, IOException
{
response.setStatusCode (HttpStatus.SC_OK);
response.setEntity (new StringEntity ("0123456789"));
}
})
.create ();
server.start ();
return server.getLocalPort ();
}
示例5: process
import org.apache.http.HttpException; //导入依赖的package包/类
@Override
public void process(final HttpRequest request,
final HttpContext context) throws HttpException, IOException {
final HttpRequestAttachment.Builder builder = create("Request", request.getRequestLine().getUri())
.withMethod(request.getRequestLine().getMethod());
Stream.of(request.getAllHeaders())
.forEach(header -> builder.withHeader(header.getName(), header.getValue()));
if (request instanceof HttpEntityEnclosingRequest) {
final HttpEntity entity = ((HttpEntityEnclosingRequest) request).getEntity();
final ByteArrayOutputStream os = new ByteArrayOutputStream();
entity.writeTo(os);
final String body = new String(os.toByteArray(), StandardCharsets.UTF_8);
builder.withBody(body);
}
final HttpRequestAttachment requestAttachment = builder.build();
processor.addAttachment(requestAttachment, renderer);
}
示例6: process
import org.apache.http.HttpException; //导入依赖的package包/类
@Override
public void process(final HttpResponse response,
final HttpContext context) throws HttpException, IOException {
final HttpResponseAttachment.Builder builder = create("Response")
.withResponseCode(response.getStatusLine().getStatusCode());
Stream.of(response.getAllHeaders())
.forEach(header -> builder.withHeader(header.getName(), header.getValue()));
final ByteArrayOutputStream os = new ByteArrayOutputStream();
response.getEntity().writeTo(os);
final String body = new String(os.toByteArray(), StandardCharsets.UTF_8);
builder.withBody(body);
final HttpResponseAttachment responseAttachment = builder.build();
processor.addAttachment(responseAttachment, renderer);
}
示例7: put
import org.apache.http.HttpException; //导入依赖的package包/类
private Map put(String url, String data) throws IOException, HttpException {
Map<String,Object> map = null;
CredentialsProvider credentials = credentialsProvider();
CloseableHttpClient httpclient = HttpClients.custom()
.setDefaultCredentialsProvider(credentials)
.build();
try {
HttpPut httpPut = new HttpPut(url);
httpPut.setHeader("Accept", "application/json");
httpPut.setHeader("Content-Type", "application/json");
HttpEntity entity = new ByteArrayEntity(data.getBytes("utf-8"));
httpPut.setEntity(entity);
System.out.println("Executing request " + httpPut.getRequestLine());
CloseableHttpResponse response = httpclient.execute(httpPut);
try {
LOG.debug("----------------------------------------");
LOG.debug((String)response.getStatusLine().getReasonPhrase());
String responseBody = EntityUtils.toString(response.getEntity());
LOG.debug(responseBody);
Gson gson = new Gson();
map = new HashMap<String,Object>();
map = (Map<String,Object>) gson.fromJson(responseBody, map.getClass());
LOG.debug(responseBody);
} finally {
response.close();
}
} finally {
httpclient.close();
}
return map;
}
开发者ID:dellemc-symphony,项目名称:ticketing-service-paqx-parent-sample,代码行数:35,代码来源:TicketingIntegrationService.java
示例8: process
import org.apache.http.HttpException; //导入依赖的package包/类
@Override
public void process(HttpResponse response, HttpContext httpContext) throws HttpException, IOException {
if (!context.logger.isDebugEnabled()) {
return;
}
int id = counter.get();
StringBuilder sb = new StringBuilder();
sb.append('\n').append(id).append(" < ").append(response.getStatusLine().getStatusCode()).append('\n');
LoggingUtils.logHeaders(sb, id, '<', response);
HttpEntity entity = response.getEntity();
if (LoggingUtils.isPrintable(entity)) {
LoggingEntityWrapper wrapper = new LoggingEntityWrapper(entity);
String buffer = FileUtils.toString(wrapper.getContent());
sb.append(buffer).append('\n');
response.setEntity(wrapper);
}
context.logger.debug(sb.toString());
}
示例9: registerFields
import org.apache.http.HttpException; //导入依赖的package包/类
private void registerFields() throws IOException, HttpException, ExporterException {
String parentType = null;
List<Config.Field> parentFields = new ArrayList<Config.Field>();
int pos = 2; // Advance past timestamp and resource name
for(Config.Field fld : conf.getFields()) {
boolean isMetric = fld.hasMetric();
String name = isMetric ? fld.getMetric() : fld.getProp();
// Parse parent reference if present.
//
Matcher m = Patterns.parentPattern.matcher(name);
if(m.matches()) {
String pn = m.group(1);
if(parentType == null) {
parentType = pn;
} else if(!pn.equals(parentType))
throw new ExporterException("References to multiple parents not supported");
String fn = m.group(2);
parentFields.add(new Config.Field(fld.getAlias(), fn, isMetric));
}
if(statPos.get(fld.getMetric()) == null) {
statPos.put(name, pos);
}
++pos;
}
}
示例10: process
import org.apache.http.HttpException; //导入依赖的package包/类
public void process(final HttpRequest request, final HttpContext context)
throws HttpException, IOException {
if (request == null) {
throw new IllegalArgumentException("HTTP request may not be null");
}
String method = request.getRequestLine().getMethod();
if (method.equalsIgnoreCase("CONNECT")) {
return;
}
// Add default headers
@SuppressWarnings("unchecked")
Collection<Header> defHeaders = (Collection<Header>) request.getParams().getParameter(
ClientPNames.DEFAULT_HEADERS);
if (defHeaders != null) {
for (Header defHeader : defHeaders) {
request.addHeader(defHeader);
}
}
}
示例11: doReceiveResponse
import org.apache.http.HttpException; //导入依赖的package包/类
@Override
protected HttpResponse doReceiveResponse(
final HttpRequest request,
final HttpClientConnection conn,
final HttpContext context)
throws HttpException, IOException {
AWSRequestMetrics awsRequestMetrics = (AWSRequestMetrics) context
.getAttribute(AWSRequestMetrics.class.getSimpleName());
if (awsRequestMetrics == null) {
return super.doReceiveResponse(request, conn, context);
}
awsRequestMetrics.startEvent(Field.HttpClientReceiveResponseTime);
try {
return super.doReceiveResponse(request, conn, context);
} finally {
awsRequestMetrics.endEvent(Field.HttpClientReceiveResponseTime);
}
}
示例12: requestHttpGet
import org.apache.http.HttpException; //导入依赖的package包/类
public String requestHttpGet(String url_prex, String type) throws HttpException, IOException {
String url = url_prex + type;
HttpRequestBase method = this.httpGetMethod(url, "");
method.setConfig(requestConfig);
long start = System.currentTimeMillis();
HttpResponse response = client.execute(method);
long end = System.currentTimeMillis();
Logger.getGlobal().log(Level.INFO, String.valueOf(end - start));
HttpEntity entity = response.getEntity();
if (entity == null) {
return "";
}
InputStream is = null;
String responseData = "";
try {
is = entity.getContent();
responseData = IOUtils.toString(is, "UTF-8");
} finally {
if (is != null) {
is.close();
}
}
return responseData;
}
示例13: process
import org.apache.http.HttpException; //导入依赖的package包/类
public void process(final HttpRequest request, final HttpContext context)
throws HttpException, IOException {
if (request == null) {
throw new IllegalArgumentException("HTTP request may not be null");
}
String method = request.getRequestLine().getMethod();
if (method.equalsIgnoreCase("CONNECT")) {
return;
}
if (!request.containsHeader(HTTP.CONN_DIRECTIVE)) {
// Default policy is to keep connection alive
// whenever possible
request.addHeader(HTTP.CONN_DIRECTIVE, HTTP.CONN_KEEP_ALIVE);
}
}
示例14: handleException
import org.apache.http.HttpException; //导入依赖的package包/类
/**
* Handles the given exception and generates an HTTP response to be sent
* back to the client to inform about the exceptional condition encountered
* in the course of the request processing.
*
* @param ex the exception.
* @param response the HTTP response.
*/
protected void handleException(final HttpException ex, final HttpResponse response) {
if (ex instanceof MethodNotSupportedException) {
response.setStatusCode(HttpStatus.SC_NOT_IMPLEMENTED);
} else if (ex instanceof UnsupportedHttpVersionException) {
response.setStatusCode(HttpStatus.SC_HTTP_VERSION_NOT_SUPPORTED);
} else if (ex instanceof ProtocolException) {
response.setStatusCode(HttpStatus.SC_BAD_REQUEST);
} else {
response.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);
}
String message = ex.getMessage();
if (message == null) {
message = ex.toString();
}
byte[] msg = EncodingUtils.getAsciiBytes(message);
ByteArrayEntity entity = new ByteArrayEntity(msg);
entity.setContentType("text/plain; charset=US-ASCII");
response.setEntity(entity);
}
示例15: execute
import org.apache.http.HttpException; //导入依赖的package包/类
@Override
public CloseableHttpResponse execute(HttpRoute route, HttpRequestWrapper request, HttpClientContext clientContext,
HttpExecutionAware execAware) throws IOException, HttpException {
Proxy proxy = (Proxy) clientContext.getAttribute(VSCrawlerConstant.VSCRAWLER_AVPROXY_KEY);
if (proxy != null) {
proxy.recordUsage();
}
try {
return delegate.execute(route, request, clientContext, execAware);
} catch (IOException ioe) {
if (proxy != null) {
proxy.recordFailed();
}
throw ioe;
}
}