List of usage examples for org.apache.http.client.methods HttpUriRequest getURI
URI getURI();
From source file:com.iflytek.iFramework.http.asynhttp.AsyncHttpClient.java
/** * Puts a new request in queue as a new thread in pool to be executed * * @param client HttpClient to be used for request, can differ in single requests * @param contentType MIME body type, for POST and PUT requests, may be null * @param context Context of Android application, to hold the reference of request * @param httpContext HttpContext in which the request will be executed * @param responseHandler ResponseHandler or its subclass to put the response into * @param uriRequest instance of HttpUriRequest, which means it must be of HttpDelete, * HttpPost, HttpGet, HttpPut, etc. * @return RequestHandle of future request process *//* w ww. j a va2s . co m*/ protected RequestHandle sendRequest(DefaultHttpClient client, HttpContext httpContext, HttpUriRequest uriRequest, String contentType, ResponseHandlerInterface responseHandler, Context context) { if (uriRequest == null) { throw new IllegalArgumentException("HttpUriRequest must not be null"); } if (responseHandler == null) { throw new IllegalArgumentException("ResponseHandler must not be null"); } if (responseHandler.getUseSynchronousMode()) { throw new IllegalArgumentException( "Synchronous ResponseHandler used in AsyncHttpClient. You should create your response handler in a looper thread or use SyncHttpClient instead."); } if (contentType != null) { uriRequest.setHeader(HEADER_CONTENT_TYPE, contentType); } responseHandler.setRequestHeaders(uriRequest.getAllHeaders()); responseHandler.setRequestURI(uriRequest.getURI()); AsyncHttpRequest request = newAsyncHttpRequest(client, httpContext, uriRequest, contentType, responseHandler, context); threadPool.submit(request); RequestHandle requestHandle = new RequestHandle(request); if (context != null) { // Add request to request map List<RequestHandle> requestList = requestMap.get(context); if (requestList == null) { requestList = new LinkedList<RequestHandle>(); requestMap.put(context, requestList); } if (responseHandler instanceof RangeFileAsyncHttpResponseHandler) ((RangeFileAsyncHttpResponseHandler) responseHandler).updateRequestHeaders(uriRequest); requestList.add(requestHandle); Iterator<RequestHandle> iterator = requestList.iterator(); while (iterator.hasNext()) { if (iterator.next().shouldBeGarbageCollected()) { iterator.remove(); } } } return requestHandle; }
From source file:com.appbase.androidquery.callback.AbstractAjaxCallback.java
private void httpDo(HttpUriRequest hr, String url, Map<String, String> headers, AjaxStatus status) throws ClientProtocolException, IOException { if (AGENT != null) { hr.addHeader("User-Agent", AGENT); }//from w w w . j a v a 2s . co m if (headers != null) { for (String name : headers.keySet()) { hr.addHeader(name, headers.get(name)); } } if (GZIP && (headers == null || !headers.containsKey("Accept-Encoding"))) { hr.addHeader("Accept-Encoding", "gzip"); } String cookie = makeCookie(); if (cookie != null) { hr.addHeader("Cookie", cookie); } if (ah != null) { ah.applyToken(this, hr); } DefaultHttpClient client = getClient(); HttpParams hp = hr.getParams(); if (proxy != null) hp.setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy); if (timeout > 0) { hp.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, timeout); hp.setParameter(CoreConnectionPNames.SO_TIMEOUT, timeout); } HttpContext context = new BasicHttpContext(); CookieStore cookieStore = new BasicCookieStore(); context.setAttribute(ClientContext.COOKIE_STORE, cookieStore); request = hr; if (abort) { throw new IOException("Aborted"); } HttpResponse response = null; try { //response = client.execute(hr, context); response = execute(hr, client, context); } catch (HttpHostConnectException e) { //if proxy is used, automatically retry without proxy if (proxy != null) { AQUtility.debug("proxy failed, retrying without proxy"); hp.setParameter(ConnRoutePNames.DEFAULT_PROXY, null); //response = client.execute(hr, context); response = execute(hr, client, context); } else { throw e; } } byte[] data = null; String redirect = url; int code = response.getStatusLine().getStatusCode(); String message = response.getStatusLine().getReasonPhrase(); String error = null; HttpEntity entity = response.getEntity(); File file = null; if (code < 200 || code >= 300) { InputStream is = null; try { if (entity != null) { is = entity.getContent(); byte[] s = toData(getEncoding(entity), is); error = new String(s, "UTF-8"); AQUtility.debug("error", error); } } catch (Exception e) { AQUtility.debug(e); } finally { AQUtility.close(is); } } else { HttpHost currentHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST); HttpUriRequest currentReq = (HttpUriRequest) context.getAttribute(ExecutionContext.HTTP_REQUEST); redirect = currentHost.toURI() + currentReq.getURI(); int size = Math.max(32, Math.min(1024 * 64, (int) entity.getContentLength())); OutputStream os = null; InputStream is = null; try { file = getPreFile(); if (file == null) { os = new PredefinedBAOS(size); } else { file.createNewFile(); os = new BufferedOutputStream(new FileOutputStream(file)); } is = entity.getContent(); if ("gzip".equalsIgnoreCase(getEncoding(entity))) { is = new GZIPInputStream(is); } copy(is, os, (int) entity.getContentLength()); os.flush(); if (file == null) { data = ((PredefinedBAOS) os).toByteArray(); } else { if (!file.exists() || file.length() == 0) { file = null; } } } finally { AQUtility.close(is); AQUtility.close(os); } } AQUtility.debug("response", code); if (data != null) { AQUtility.debug(data.length, url); } status.code(code).message(message).error(error).redirect(redirect).time(new Date()).data(data).file(file) .client(client).context(context).headers(response.getAllHeaders()); }
From source file:com.android.yijiang.kzx.http.AsyncHttpClient.java
/** * Puts a new request in queue as a new thread in pool to be executed * * @param client HttpClient to be used for request, can differ in single requests * @param contentType MIME body type, for POST and PUT requests, may be null * @param context Context of Android application, to hold the reference of request * @param httpContext HttpContext in which the request will be executed * @param responseHandler ResponseHandler or its subclass to put the response into * @param uriRequest instance of HttpUriRequest, which means it must be of HttpDelete, * HttpPost, HttpGet, HttpPut, etc. * @return RequestHandle of future request process *///from w w w . j a v a 2s. c om protected RequestHandle sendRequest(DefaultHttpClient client, HttpContext httpContext, HttpUriRequest uriRequest, String contentType, ResponseHandlerInterface responseHandler, Context context) { if (uriRequest == null) { throw new IllegalArgumentException("HttpUriRequest must not be null"); } if (responseHandler == null) { throw new IllegalArgumentException("ResponseHandler must not be null"); } if (responseHandler.getUseSynchronousMode()) { throw new IllegalArgumentException( "Synchronous ResponseHandler used in AsyncHttpClient. You should create your response handler in a looper thread or use SyncHttpClient instead."); } if (contentType != null) { uriRequest.setHeader(HEADER_CONTENT_TYPE, contentType); } responseHandler.setRequestHeaders(uriRequest.getAllHeaders()); responseHandler.setRequestURI(uriRequest.getURI()); AsyncHttpRequest request = newAsyncHttpRequest(client, httpContext, uriRequest, contentType, responseHandler, context); threadPool.submit(request); RequestHandle requestHandle = new RequestHandle(request); if (context != null) { // Add request to request map List<RequestHandle> requestList = requestMap.get(context); synchronized (requestMap) { if (requestList == null) { requestList = Collections.synchronizedList(new LinkedList<RequestHandle>()); requestMap.put(context, requestList); } } if (responseHandler instanceof RangeFileAsyncHttpResponseHandler) ((RangeFileAsyncHttpResponseHandler) responseHandler).updateRequestHeaders(uriRequest); requestList.add(requestHandle); Iterator<RequestHandle> iterator = requestList.iterator(); while (iterator.hasNext()) { if (iterator.next().shouldBeGarbageCollected()) { iterator.remove(); } } } return requestHandle; }
From source file:net.yacy.cora.protocol.http.HTTPClient.java
private void execute(final HttpUriRequest httpUriRequest, final boolean concurrent) throws IOException { final HttpClientContext context = HttpClientContext.create(); context.setRequestConfig(reqConfBuilder.build()); if (this.host != null) context.setTargetHost(new HttpHost(this.host)); setHeaders(httpUriRequest);/*w w w . jav a2s .c o m*/ // statistics storeConnectionInfo(httpUriRequest); // execute the method; some asserts confirm that that the request can be send with Content-Length and is therefore not terminated by EOF if (httpUriRequest instanceof HttpEntityEnclosingRequest) { final HttpEntityEnclosingRequest hrequest = (HttpEntityEnclosingRequest) httpUriRequest; final HttpEntity entity = hrequest.getEntity(); assert entity != null; //assert !entity.isChunked(); //assert entity.getContentLength() >= 0; assert !hrequest.expectContinue(); } final String initialThreadName = Thread.currentThread().getName(); Thread.currentThread().setName("HTTPClient-" + httpUriRequest.getURI()); final long time = System.currentTimeMillis(); try { if (concurrent) { FutureTask<CloseableHttpResponse> t = new FutureTask<CloseableHttpResponse>( new Callable<CloseableHttpResponse>() { @Override public CloseableHttpResponse call() throws ClientProtocolException, IOException { final CloseableHttpClient client = clientBuilder.build(); CloseableHttpResponse response = client.execute(httpUriRequest, context); return response; } }); executor.execute(t); try { this.httpResponse = t.get(this.timeout, TimeUnit.MILLISECONDS); } catch (ExecutionException e) { throw e.getCause(); } catch (Throwable e) { } try { t.cancel(true); } catch (Throwable e) { } if (this.httpResponse == null) throw new IOException("timout to client after " + this.timeout + "ms" + " for url " + httpUriRequest.getURI().toString()); } else { final CloseableHttpClient client = clientBuilder.build(); this.httpResponse = client.execute(httpUriRequest, context); } this.httpResponse.setHeader(HeaderFramework.RESPONSE_TIME_MILLIS, Long.toString(System.currentTimeMillis() - time)); } catch (final Throwable e) { ConnectionInfo.removeConnection(httpUriRequest.hashCode()); httpUriRequest.abort(); if (this.httpResponse != null) this.httpResponse.close(); //e.printStackTrace(); throw new IOException( "Client can't execute: " + (e.getCause() == null ? e.getMessage() : e.getCause().getMessage()) + " duration=" + Long.toString(System.currentTimeMillis() - time) + " for url " + httpUriRequest.getURI().toString()); } finally { /* Restore the thread initial name */ Thread.currentThread().setName(initialThreadName); } }
From source file:com.betfair.testing.utils.cougar.helpers.CougarHelpers.java
/** * Send a request to a locally running Cougar container via REST as per the * passed parameters./* w w w . jav a 2 s. c o m*/ */ public HttpResponseBean makeRestCougarHTTPCall(HttpCallBean httpCallBean, HttpUriRequest method, CougarMessageProtocolRequestTypeEnum protocolRequestType, CougarMessageContentTypeEnum responseContentTypeEnum, CougarMessageContentTypeEnum requestContentTypeEnum) { Map<String, String> headerParams = httpCallBean.getHeaderParams(); String authority = httpCallBean.getAuthority(); Map<String, String> authCredentials = httpCallBean.getAuthCredentials(); Map<String, String> acceptProtocols = httpCallBean.getAcceptProtocols(); String ipAddress = httpCallBean.getIpAddress(); String altUrl = httpCallBean.getAlternativeURL(); Object postQueryObject = httpCallBean.getPostQueryObjectsByEnum(protocolRequestType); String postQuery; if (postQueryObject == null) { postQuery = null; } else { postQuery = (String) postQueryObject; } InputStream inputStream = null; try { completeRestMethodBuild(method, responseContentTypeEnum, requestContentTypeEnum, postQuery, headerParams, authority, authCredentials, altUrl, acceptProtocols, ipAddress); if (logger.isDebugEnabled()) { logger.debug("Request"); logger.debug("======="); logger.debug("URI: '" + method.getURI() + "'"); Header[] headers = method.getAllHeaders(); for (Header h : headers) { logger.debug("Header: '" + h.getName() + " = " + h.getValue() + "'"); } logger.debug("Body: '" + postQuery + "'"); } Date requestTime = new Date(); final HttpResponse httpResponse = cougarDAO.executeHttpMethodBaseCall(method); inputStream = httpResponse.getEntity().getContent(); String response = buildResponseString(inputStream); if (logger.isDebugEnabled()) { logger.debug("Response"); logger.debug("========"); logger.debug(String.valueOf(httpResponse.getStatusLine())); Header[] headers = httpResponse.getAllHeaders(); for (Header h : headers) { logger.debug("Header: '" + h.getName() + " = " + h.getValue() + "'"); } logger.debug("Body: '" + response + "'"); } Date responseTime = new Date(); return buildHttpResponseBean(httpResponse, response, requestTime, responseTime); } catch (IOException e) { throw new RuntimeException(e); } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { /*ignore*/} } } }
From source file:com.seo.support.http.AsyncHttpClient.java
/** * Puts a new request in queue as a new thread in pool to be executed * /*from ww w. ja v a 2 s. c om*/ * @param client * HttpClient to be used for request, can differ in single * requests * @param contentType * MIME body type, for POST and PUT requests, may be null * @param context * Context of Android application, to hold the reference of * request * @param httpContext * HttpContext in which the request will be executed * @param responseHandler * ResponseHandler or its subclass to put the response into * @param uriRequest * instance of HttpUriRequest, which means it must be of * HttpDelete, HttpPost, HttpGet, HttpPut, etc. * @return RequestHandle of future request process */ protected RequestHandle sendRequest(DefaultHttpClient client, HttpContext httpContext, HttpUriRequest uriRequest, String contentType, ResponseHandlerInterface responseHandler, Context context) { if (uriRequest == null) { throw new IllegalArgumentException("HttpUriRequest must not be null"); } if (responseHandler == null) { throw new IllegalArgumentException("ResponseHandler must not be null"); } if (responseHandler.getUseSynchronousMode()) { throw new IllegalArgumentException( "Synchronous ResponseHandler used in AsyncHttpClient. You should create your response handler in a looper thread or use SyncHttpClient instead."); } if (contentType != null) { uriRequest.setHeader("Content-Type", contentType); } responseHandler.setRequestHeaders(uriRequest.getAllHeaders()); responseHandler.setRequestURI(uriRequest.getURI()); AsyncHttpRequest request = new AsyncHttpRequest(client, httpContext, uriRequest, responseHandler); threadPool.submit(request); RequestHandle requestHandle = new RequestHandle(request); if (context != null) { // Add request to request map List<RequestHandle> requestList = requestMap.get(context); if (requestList == null) { requestList = new LinkedList(); requestMap.put(context, requestList); } if (responseHandler instanceof RangeFileAsyncHttpResponseHandler) ((RangeFileAsyncHttpResponseHandler) responseHandler).updateRequestHeaders(uriRequest); requestList.add(requestHandle); Iterator<RequestHandle> iterator = requestList.iterator(); while (iterator.hasNext()) { if (iterator.next().shouldBeGarbageCollected()) { iterator.remove(); } } } return requestHandle; }
From source file:org.eclipse.rdf4j.http.client.SPARQLProtocolSession.java
/** * Parse the response in this thread using the provided {@link RDFHandler}. All HTTP connections are * closed and released in this method/*from w w w. j ava 2s.c om*/ */ protected void getRDF(HttpUriRequest method, RDFHandler handler, boolean requireContext) throws IOException, RDFHandlerException, RepositoryException, MalformedQueryException, UnauthorizedException, QueryInterruptedException { // Specify which formats we support using Accept headers Set<RDFFormat> rdfFormats = RDFParserRegistry.getInstance().getKeys(); if (rdfFormats.isEmpty()) { throw new RepositoryException("No tuple RDF parsers have been registered"); } // send the tuple query HttpResponse response = sendGraphQueryViaHttp(method, requireContext, rdfFormats); try { String mimeType = getResponseMIMEType(response); try { RDFFormat format = RDFFormat.matchMIMEType(mimeType, rdfFormats) .orElseThrow(() -> new RepositoryException( "Server responded with an unsupported file format: " + mimeType)); RDFParser parser = Rio.createParser(format, getValueFactory()); parser.setParserConfig(getParserConfig()); parser.setParseErrorListener(new ParseErrorLogger()); parser.setRDFHandler(handler); parser.parse(response.getEntity().getContent(), method.getURI().toASCIIString()); } catch (RDFParseException e) { throw new RepositoryException("Malformed query result from server", e); } } finally { EntityUtils.consumeQuietly(response.getEntity()); } }
From source file:cn.openwatch.internal.http.loopj.AsyncHttpClient.java
/** * Puts a new request in queue as a new thread in pool to be executed * * @param client HttpClient to be used for request, can differ in single * requests//from w ww .j a v a2s . c o m * @param contentType MIME body type, for POST and PUT requests, may be null * @param context Context of Android application, to hold the reference of * request * @param httpContext HttpContext in which the request will be executed * @param responseHandler ResponseHandler or its subclass to put the response into * @param uriRequest instance of HttpUriRequest, which means it must be of * HttpDelete, HttpPost, HttpGet, HttpPut, etc. * @return RequestHandle of future request process */ protected RequestHandle sendRequest(DefaultHttpClient client, HttpContext httpContext, HttpUriRequest uriRequest, String contentType, ResponseHandlerInterface responseHandler, Context context) { if (uriRequest == null) { throw new IllegalArgumentException("HttpUriRequest must not be null"); } if (responseHandler == null) { throw new IllegalArgumentException("ResponseHandler must not be null"); } if (responseHandler.getUseSynchronousMode() && !responseHandler.getUsePoolThread()) { throw new IllegalArgumentException( "Synchronous ResponseHandler used in AsyncHttpClient. You should create your response handler in a looper thread or use SyncHttpClient instead."); } if (contentType != null) { if (uriRequest instanceof HttpEntityEnclosingRequestBase && ((HttpEntityEnclosingRequestBase) uriRequest).getEntity() != null && uriRequest.containsHeader(HEADER_CONTENT_TYPE)) { } else { uriRequest.setHeader(HEADER_CONTENT_TYPE, contentType); } } responseHandler.setRequestHeaders(uriRequest.getAllHeaders()); responseHandler.setRequestURI(uriRequest.getURI()); AsyncHttpRequest request = newAsyncHttpRequest(client, httpContext, uriRequest, contentType, responseHandler, context); threadPool.submit(request); RequestHandle requestHandle = new RequestHandle(request); if (context != null) { List<RequestHandle> requestList; // Add request to request map synchronized (requestMap) { requestList = requestMap.get(context); if (requestList == null) { requestList = Collections.synchronizedList(new LinkedList<RequestHandle>()); requestMap.put(context, requestList); } } requestList.add(requestHandle); Iterator<RequestHandle> iterator = requestList.iterator(); while (iterator.hasNext()) { if (iterator.next().shouldBeGarbageCollected()) { iterator.remove(); } } } return requestHandle; }
From source file:com.activiti.service.activiti.ActivitiClientService.java
public AttachmentResponseInfo executeDownloadRequest(HttpUriRequest request, String userName, String password, Integer... expectedStatusCodes) { ActivitiServiceException exception = null; CloseableHttpClient client = getHttpClient(userName, password); try {/* w w w. j av a 2s . c o m*/ CloseableHttpResponse response = client.execute(request); try { int statusCode = -1; if (response.getStatusLine() != null) { statusCode = response.getStatusLine().getStatusCode(); } boolean success = Arrays.asList(expectedStatusCodes).contains(statusCode); if (success) { if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { String contentDispositionFileName[] = response.getHeaders("Content-Disposition")[0] .getValue().split("="); String fileName = contentDispositionFileName[contentDispositionFileName.length - 1]; return new AttachmentResponseInfo(fileName, IOUtils.toByteArray(response.getEntity().getContent())); } else { return new AttachmentResponseInfo(statusCode, readJsonContent(response.getEntity().getContent())); } } else { exception = new ActivitiServiceException( extractError(readJsonContent(response.getEntity().getContent()), "An error occured while calling Activiti: " + response.getStatusLine())); } } catch (Exception e) { log.warn("Error consuming response from uri " + request.getURI(), e); exception = wrapException(e, request); } finally { response.close(); } } catch (Exception e) { log.error("Error executing request to uri " + request.getURI(), e); exception = wrapException(e, request); } finally { try { client.close(); } catch (Exception e) { log.warn("Error closing http client instance", e); } } if (exception != null) { throw exception; } return null; }