下面列出了org.apache.http.client.methods.HttpExecutionAware#org.apache.http.HttpException 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Override
protected Void handleAllowedRequestWithBackend(HttpRequest request, HttpAsyncExchange exchange, HttpContext context) throws HttpException, IOException {
Map<String, String> params = HttpServerUtilities.parseSimplePostParameters(request);
if (params == null) {
return HttpServerUtilities.prepareHttpResponse(exchange, 400, "Failed to get POST parameters.");
}
String path = params.get("path");
if (path == null) {
return HttpServerUtilities.prepareHttpResponse(exchange, 400, "Path must be provided.");
}
if (!Files.isRegularFile(Paths.get(path))) {
return HttpServerUtilities.prepareHttpResponse(exchange, 400, "Path '" + path + "' is not a file.");
}
backEndHolder.importTasks(new File(path));
return emptySuccessResponse(exchange);
}
@Override
public String future_position(String symbol, String contractType)
throws HttpException, IOException {
// 构造参数签名
Map<String, String> params = new HashMap<String, String>();
if (!StringUtil.isEmpty(symbol )) {
params.put("symbol", symbol);
}
if (!StringUtil.isEmpty(contractType )) {
params.put("contract_type", contractType);
}
params.put("api_key", api_key);
String sign = MD5Util.buildMysignV1(params, secret_key);
params.put("sign", sign);
// 发送post请求
HttpUtilManager httpUtil = HttpUtilManager.getInstance();
String result = httpUtil.requestHttpPost(url_prex,this.FUTURE_POSITION_URL,
params);
// System.out.println(result);
return result;
}
@Override
public void process(final HttpResponse response, final HttpContext context)
throws HttpException, IOException {
final HttpEntity entity = response.getEntity();
final Header encoding = entity.getContentEncoding();
if (encoding != null) {
for (final HeaderElement element : encoding.getElements()) {
if (element.getName().equalsIgnoreCase(
GzipResponseInterceptor.ENCODING_GZIP)) {
response.setEntity(new GzipDecompressingEntity(response
.getEntity()));
break;
}
}
}
}
@Override
protected final Void handleAllowedRequestWithBackend(HttpRequest request, HttpAsyncExchange exchange, HttpContext context)
throws HttpException, IOException {
Map<String, String> params = HttpServerUtilities.parseSimplePostParameters(request);
if (params == null) {
return HttpServerUtilities.prepareHttpResponse(exchange, 400, "Failed to get POST parameters.");
}
String id = params.get("id");
if (id == null) {
return HttpServerUtilities.prepareHttpResponse(exchange, 400, "Failed to get task activation constructor ID.");
}
TaskActivationConstructor constructor = taskActivationConstructorManager.get(id);
if (constructor == null) {
return HttpServerUtilities.prepareHttpResponse(exchange, 404, "No constructor found for ID '" + id + "'.");
}
return handleRequestWithBackendAndConstructor(exchange, constructor, params);
}
public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException {
AuthState authState = (AuthState) context.getAttribute(ClientContext.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 (requestMethod.equals(HttpPut.METHOD_NAME) || requestMethod.equals(HttpPost.METHOD_NAME)) {
CredentialsProvider credentialsProvider = (CredentialsProvider) context.getAttribute(ClientContext.CREDS_PROVIDER);
HttpHost targetHost = (HttpHost) context.getAttribute(ExecutionContext.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);
}
}
@Test
public void testSyntheticColumns() throws IOException, LongRunningQueryException, InterruptedException, HttpException, URISyntaxException {
ControlFile cf = getTestControlFile();
ControlFileModel model = getTestModel(cf);
String fieldName = "testLoc";
LocationColumn location = new LocationColumn();
location.address = "1234 fake street";
location.latitude = "90";
location.longitude = "90";
//Test that we can add to the synthetic location when none exist
model.setSyntheticLocation(fieldName,location);
TestCase.assertEquals(model.getSyntheticLocations().get(fieldName),location);
//Test that we can add another one when one already exists
String anotherColumn = "anotherColumn";
LocationColumn newLocation = new LocationColumn();
newLocation.address = "742 evergreen terrace";
model.setSyntheticLocation(anotherColumn,newLocation);
TestCase.assertEquals(model.getSyntheticLocations().get(anotherColumn), newLocation);
}
@Override
protected RequestDirector createClientRequestDirector(
HttpRequestExecutor requestExec,
ClientConnectionManager conman,
ConnectionReuseStrategy reustrat,
ConnectionKeepAliveStrategy kastrat,
HttpRoutePlanner rouplan,
HttpProcessor httpProcessor,
HttpRequestRetryHandler retryHandler,
RedirectHandler redirectHandler,
AuthenticationHandler targetAuthHandler,
AuthenticationHandler proxyAuthHandler,
UserTokenHandler stateHandler,
HttpParams params) {
return new RequestDirector() {
@Beta
public HttpResponse execute(HttpHost target, HttpRequest request, HttpContext context)
throws HttpException, IOException {
return new BasicHttpResponse(HttpVersion.HTTP_1_1, responseCode, null);
}
};
}
@Override
protected void handleWithBackend(HttpRequest request, HttpAsyncExchange exchange, HttpContext context)
throws HttpException, IOException {
String method = request.getRequestLine().getMethod();
if (!method.equalsIgnoreCase(ACCEPTED_METHOD)) {
LOGGER.warning("Ignoring request with unknown method " + method);
CliRpcCodec.prepareResponse(exchange, 400, "Method must be " + ACCEPTED_METHOD);
return;
}
JsonNode requestData = CliRpcCodec.decodeRequest(getRequestBody(request));
if (requestData == null) {
LOGGER.warning("Failed to parse request into JSON!");
CliRpcCodec.prepareResponse(exchange, 400, "Cannot parse request!");
return;
}
handleTaskActionWithBackend(exchange, requestData);
}
public static void download(String url, String path,
final IOAuthCallBack iOAuthCallBack) {
HttpUtils http = new HttpUtils();
HttpHandler<File> handler = http.download(url, path, false, // 如果目标文件存在,接着未完成的部分继续下载。服务器不支持RANGE时将从新下载。
false, // 如果从请求返回信息中获取到文件名,下载完成后自动重命名。
new RequestCallBack<File>() {
@Override
public void onSuccess(ResponseInfo<File> arg0) {
if (d)
Log.d("-----downfile-----", "success");
iOAuthCallBack.getIOAuthCallBack(arg0.result.getName(),
0);
}
@Override
public void onFailure(com.lidroid.xutils.exception.HttpException e, String s) {
if (d)
Log.d("-----downfile-----", "fail");
iOAuthCallBack.getIOAuthCallBack(e.toString(), 1);
}
});
}
@Override
protected String doExecute(final HttpClient httpClient) throws IOException, HttpException {
final HttpPost addPageRequest = new HttpPost(getURLBase() + PORTAL_ADD_PAGE_API);
addPageRequest.setHeader(API_TOKEN_HEADER, getAPITokenFromCookie());
final EntityBuilder entityBuilder = EntityBuilder.create();
entityBuilder.setContentType(ContentType.APPLICATION_JSON);
entityBuilder.setText(String.format("{\"pageZip\" : \"%s\" }", uploadedFileToken));
addPageRequest.setEntity(entityBuilder.build());
final HttpResponse response = httpClient.execute(addPageRequest);
final int status = response.getStatusLine().getStatusCode();
String responseContent = contentAsString(response);
if (status != HttpURLConnection.HTTP_OK) {
throw new HttpException(responseContent.isEmpty() ? String.format("Add custom page failed with status: %s. Open Engine log for more details.", status) : responseContent);
}
return responseContent;
}
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) {
CredentialsProvider credsProvider = (CredentialsProvider) context
.getAttribute(HttpClientContext.CREDS_PROVIDER);
HttpHost targetHost = (HttpHost) context.getAttribute(HttpClientContext.HTTP_TARGET_HOST);
Credentials creds = credsProvider
.getCredentials(new AuthScope(targetHost.getHostName(), targetHost.getPort()));
if (creds == null) {
throw new HttpException("No credentials given for preemptive authentication");
}
authState.update(authScheme, creds);
}
}
@Override
public String ticker(String symbol) throws HttpException, IOException {
HttpUtilManager httpUtil = HttpUtilManager.getInstance();
String param = "";
// if(!StringUtil.isEmpty(symbol )) {
// if (!param.equals("")) {
// param += "&";
// }
// param += "symbol=" + symbol;
// }
String[] params = {"secret_key=" + secret_key,"symbol=" + symbol, "api_key=" + api_key};
params = StringSort.getUrlParam(params);
param = StringSort.getText(params, "&");
param = param + "&sign=" + CryptoUtils.encodeMD5(param);
String result = httpUtil.requestHttpGet(url_prex, TICKER_URL, param);
return result;
}
@Override
public HttpRoute determineRoute(HttpHost host, HttpRequest request, HttpContext context) throws HttpException {
try {
ClientCredential clientCredential = binding.getClientCredentialProvider().getClientCredential(binding.map(request));
String hostname = clientCredential.getHost();
int port = -1;
final int pos = hostname.lastIndexOf(":");
if (pos > 0) {
try {
port = Integer.parseInt(hostname.substring(pos + 1));
} catch (NumberFormatException ex) {
throw new IllegalArgumentException("Host contains invalid port number: " + hostname);
}
hostname = hostname.substring(0, pos);
}
HttpHost target = new HttpHost(hostname, port, "https");
return super.determineRoute(target, request, context);
} catch (NoMatchingCredentialException e) {
throw new RuntimeException(e);
}
}
@Override
protected String doExecute(final HttpClient httpClient) throws IOException, HttpException {
final HttpPut updatePageRequest = new HttpPut(
String.format(getURLBase() + PORTAL_UPDATE_PAGE_API, pageToUpdate.getId()));
updatePageRequest.setHeader(API_TOKEN_HEADER, getAPITokenFromCookie());
final EntityBuilder entityBuilder = EntityBuilder.create();
entityBuilder.setContentType(ContentType.APPLICATION_JSON);
if(pageToUpdate.getProcessDefinitionId() != null) {
entityBuilder.setText(String.format("{\"pageZip\" : \"%s\", \"processDefinitionId\" : \"%s\" }", uploadedFileToken,pageToUpdate.getProcessDefinitionId()));
}else {
entityBuilder.setText(String.format("{\"pageZip\" : \"%s\" }", uploadedFileToken));
}
updatePageRequest.setEntity(entityBuilder.build());
final HttpResponse response = httpClient.execute(updatePageRequest);
final int status = response.getStatusLine().getStatusCode();
String responseContent = contentAsString(response);
if (status != HttpURLConnection.HTTP_OK) {
throw new HttpException(responseContent.isEmpty() ? String.format("Add custom page failed with status: %s. Open Engine log for more details.", status) : responseContent);
}
return responseContent;
}
@Override
protected String doExecute(HttpClient httpClient) throws IOException, HttpException {
final HttpGet request = new HttpGet(
String.format("%s%s?p=0&c=%s", getURLBase(), PORTAL_BONITA_PAGE_API, Integer.MAX_VALUE));
request.setHeader(API_TOKEN_HEADER, getAPITokenFromCookie());
HttpResponse response = httpClient.execute(request);
if (response.getStatusLine().getStatusCode() != HttpURLConnection.HTTP_OK) {
throw new HttpException(
String.format("Bonita Pages request failed with status: %s", response.getStatusLine().getStatusCode()));
}
return contentAsString(response);
}
protected void handleDiscoverRequest(HttpRequest request, HttpResponse response, HttpContext context)
throws HttpException, IOException {
response.setStatusCode(200);
response.setHeader("Cache-Control", "public, max-age=31536000");
response.setEntity(new StringEntity("{\"jwks_uri\": \"" + uri + CTX_KEYS + "\",\n" + "\"issuer\": \"" + uri
+ "\", \"unknownPropertyToBeIgnored\": 42}"));
}
@Override
public void handle(HttpRequest request, HttpResponse response, HttpContext context)
throws HttpException, IOException {
Navigator<MutableMap<Object, Object>> j = Jsonya.newInstance().map();
BasicHttpRequest req = (BasicHttpRequest)request;
String url = req.getRequestLine().getUri();
URI uri = URI.create(url);
String method = req.getRequestLine().getMethod();
boolean expectsPost = uri.getPath().equals("/post");
if (expectsPost && !method.equals("POST") ||
!expectsPost && !method.equals("GET")) {
throw new IllegalStateException("Method " + method + " not allowed on " + url);
}
List<NameValuePair> params = URLEncodedUtils.parse(uri, "UTF-8");
if (!params.isEmpty()) {
j.push().at("args");
for (NameValuePair param : params) {
j.put(param.getName(), param.getValue());
}
j.pop();
}
j.put("origin", "127.0.0.1");
j.put("url", serverUrl + url);
response.setHeader("Content-Type", "application/json");
response.setStatusCode(200);
response.setEntity(new StringEntity(j.toString()));
}
public static AppException network(Exception e) {
if (e instanceof UnknownHostException || e instanceof ConnectException) {
return new AppException(TYPE_NETWORK, 0, e);
} else if (e instanceof HttpException) {
return http(e);
} else if (e instanceof SocketException) {
return socket(e);
}
return http(e);
}
public void headerRequest(HttpHost target, HttpRoute route, HttpClientConnection conn, PoolingHttpClientConnectionManager cm)
throws IOException, HttpException {
HttpRequest req = new BasicHttpRequest("OPTIONS", "*", HttpVersion.HTTP_1_1);
req.addHeader("Host", target.getHostName());
if (!conn.isOpen()) {
// establish connection based on its route info
cm.connect(conn, route, 1000, context);
// and mark it as route complete
cm.routeComplete(conn, route, context);
}
conn.sendRequestHeader(req);
conn.flush();
conn.receiveResponseHeader();
}
public void handle(HttpRequest request, HttpResponse response, HttpContext context) throws HttpException,
IOException
{
try
{
String method = request.getRequestLine().getMethod().toUpperCase(Locale.ENGLISH);
if (METHOD_GET.equals(method) || METHOD_HEAD.equals(method))
{
handleRequest(request, response, METHOD_HEAD.equals(method));
}
else if (METHOD_POST.equals(method))
{
handleRequest(request, response, METHOD_HEAD.equals(method));
}
else
{
throw new MethodNotSupportedException(MessageFormat.format(
Messages.LocalWebServerHttpRequestHandler_UNSUPPORTED_METHOD, method));
}
}
catch (Exception e)
{
IdeLog.logError(WebServerCorePlugin.getDefault(), e);
response.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);
response.setEntity(createTextEntity(Messages.LocalWebServerHttpRequestHandler_INTERNAL_SERVER_ERROR));
}
}
private static HttpRequest readPayload(final BoundSessionInputBuffer buffer) throws IOException {
DefaultHttpRequestParser requestParser = new DefaultHttpRequestParser(buffer);
try {
return requestParser.parse();
} catch (HttpException e) {
throw new WarcFormatException("Can't parse the request", e);
}
}
@Override
protected void accessToken(final DefaultHttpClient client) throws OAuth2Exception {
client.addRequestInterceptor(new HttpRequestInterceptor() {
@Override
public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException {
request.removeHeaders(HttpHeaders.AUTHORIZATION);
request.addHeader(HttpHeaders.AUTHORIZATION, OAuthClientUtils.createAuthorizationHeader(accessToken));
}
});
}
@Test
public void testExecuteWithHttpException() {
setupAuthenticate();
setupDoThrowWhenSubmitJob(new HttpException("Some message"));
try {
plugin.executeNodeStep(pluginContext, configuration, node);
Assert.fail("Expected node step failure.");
} catch (NodeStepException e) {
Assert.assertEquals("Expected failure reason to be set based on exception type",
SaltApiNodeStepFailureReason.COMMUNICATION_FAILURE, e.getFailureReason());
}
}
@Override
protected InputStream writePayload(final ByteArraySessionOutputBuffer buffer) throws IOException {
final DefaultHttpResponseWriter pw = new DefaultHttpResponseWriter(buffer);
try {
pw.write(this);
} catch (HttpException e) {
throw new RuntimeException("Unexpected HttpException.", e);
}
buffer.contentLength(buffer.size() + this.entity.getContentLength());
return new SequenceInputStream(buffer.toInputStream(), this.entity.getContent()); // TODO: we never close the getContent() inputstream...
}
@Override
protected HttpHost determineProxy(final HttpHost host,
final HttpRequest request,
final HttpContext context)
throws HttpException
{
if (noProxyFor(host.getHostName())) {
return null;
}
return proxies.get(host.getSchemeName());
}
private ExpectedResult parseExpectedResponse(Element element, Evaluator evaluator, ResultRecorder resultRecorder) {
String contents = getTextAndRemoveIndent(element);
contents = replaceVariableReferences(evaluator, contents, resultRecorder);
SessionInputBufferImpl buffer = new SessionInputBufferImpl(new HttpTransportMetricsImpl(), contents.length());
buffer.bind(new ByteArrayInputStream(contents.getBytes(StandardCharsets.UTF_8)));
DefaultHttpResponseParser defaultHttpResponseParser = new DefaultHttpResponseParser(buffer);
ExpectedResult.ExpectedResultBuilder builder = expectedResult();
String body = null;
try {
HttpResponse httpResponse = defaultHttpResponseParser.parse();
StatusLine statusLine = httpResponse.getStatusLine();
builder.withStatus(statusLine.getStatusCode());
for (Header header : httpResponse.getAllHeaders()) {
builder.withHeader(header.getName(), header.getValue());
}
if (buffer.hasBufferedData()) {
body = "";
while (buffer.hasBufferedData()) {
body += (char) buffer.read();
}
}
builder.withBody(body);
} catch (IOException | HttpException e) {
e.printStackTrace();
}
return builder.build();
}
/**
* Starts the server.
* @throws Exception in case of exception
*/
public void start() throws Exception {
final URL url = getClass().getClassLoader().getResource("insecureSSL.keystore");
final KeyStore keystore = KeyStore.getInstance("jks");
final char[] pwd = "nopassword".toCharArray();
keystore.load(url.openStream(), pwd);
final TrustManagerFactory trustManagerFactory = createTrustManagerFactory();
trustManagerFactory.init(keystore);
final TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();
final KeyManagerFactory keyManagerFactory = createKeyManagerFactory();
keyManagerFactory.init(keystore, pwd);
final KeyManager[] keyManagers = keyManagerFactory.getKeyManagers();
final SSLContext serverSSLContext = SSLContext.getInstance("TLS");
serverSSLContext.init(keyManagers, trustManagers, null);
localServer_ = new LocalTestServer(serverSSLContext);
if (html_ != null) {
final HttpRequestHandler handler = new HttpRequestHandler() {
@Override
public void handle(final HttpRequest request, final HttpResponse response, final HttpContext context)
throws HttpException, IOException {
response.setEntity(new StringEntity(html_, ContentType.TEXT_HTML));
}
};
localServer_.register("*", handler);
}
localServer_.start();
}
@Override
protected Void handleAllowedRequestWithBackend(HttpRequest request, HttpAsyncExchange exchange, HttpContext context)
throws HttpException, IOException {
Map<String, Object> data = new HashMap<>();
TaskGroup group = backEndHolder.getCurrentTaskGroup();
data.put("taskGroup", RenderedTaskGroupButton.fromTaskGroups(group, backEndHolder.getTaskGroups()));
String page = objectRenderer.render("fragments/task_groups_dropdown", data);
if (page == null) {
return HttpServerUtilities.prepareHttpResponse(exchange, 500, "Failed to render page.");
}
return HttpServerUtilities.prepareHttpResponse(exchange, HttpStatus.SC_OK, page);
}
@Override
protected HttpHost determineProxy(
final HttpHost target,
final HttpRequest request,
final HttpContext context) throws HttpException {
return doesTargetMatchNonProxyHosts(target) ? null : proxy;
}
@Override
public void process(HttpRequest request, HttpContext context) throws HttpException,
IOException {
log.info("Intercepted params: {}", context);
HttpRequestWrapper wrapper = (HttpRequestWrapper) request;
URIBuilder uribuilder = new URIBuilder(wrapper.getURI());
uribuilder.addParameter("b", "\u4321");
try {
wrapper.setURI(uribuilder.build());
} catch (URISyntaxException ex) {
throw new HttpException("Invalid request URI", ex);
}
}