List of usage examples for org.apache.http.client.methods HttpUriRequest getURI
URI getURI();
From source file:org.callimachusproject.client.HttpClientFactoryTest.java
@Test public void testTarget() throws Exception { HttpContext localContext = new BasicHttpContext(); responses.add(new BasicHttpResponse(_200)); client.execute(new HttpGet("http://example.com/200"), new ResponseHandler<Void>() { public Void handleResponse(HttpResponse response) throws ClientProtocolException, IOException { assertEquals(_200.getStatusCode(), response.getStatusLine().getStatusCode()); return null; }// w w w. j a v a2s .c o m }, localContext); HttpHost host = (HttpHost) localContext.getAttribute(ExecutionContext.HTTP_TARGET_HOST); HttpUriRequest req = (HttpUriRequest) localContext.getAttribute(ExecutionContext.HTTP_REQUEST); URI root = new URI(host.getSchemeName(), null, host.getHostName(), host.getPort(), "/", null, null); assertEquals("http://example.com/200", root.resolve(req.getURI()).toASCIIString()); }
From source file:org.callimachusproject.client.HttpClientFactoryTest.java
@Test public void test302RedirectTarget() throws Exception { HttpContext localContext = new BasicHttpContext(); HttpGet get = new HttpGet("http://example.com/302"); get.getParams().setBooleanParameter(ClientPNames.HANDLE_REDIRECTS, true); BasicHttpResponse redirect = new BasicHttpResponse(_302); redirect.setHeader("Location", "http://example.com/200"); responses.add(redirect);//w w w. j a v a2s .c om responses.add(new BasicHttpResponse(_200)); client.execute(get, new ResponseHandler<Void>() { public Void handleResponse(HttpResponse response) throws ClientProtocolException, IOException { assertEquals(_200.getStatusCode(), response.getStatusLine().getStatusCode()); return null; } }, localContext); HttpHost host = (HttpHost) localContext.getAttribute(ExecutionContext.HTTP_TARGET_HOST); HttpUriRequest req = (HttpUriRequest) localContext.getAttribute(ExecutionContext.HTTP_REQUEST); URI root = new URI(host.getSchemeName(), null, host.getHostName(), host.getPort(), "/", null, null); assertEquals("http://example.com/200", root.resolve(req.getURI()).toASCIIString()); }
From source file:com.mutu.gpstracker.breadcrumbs.GetBreadcrumbsActivitiesTask.java
/** * Retrieve the OAuth Request Token and present a browser to the user to * authorize the token./*from w ww. j a v a 2 s .c om*/ */ @Override protected Void doInBackground(Void... params) { mActivities = new LinkedList<Pair<Integer, String>>(); HttpEntity responseEntity = null; try { HttpUriRequest request = new HttpGet("http://api.gobreadcrumbs.com/v1/activities.xml"); if (isCancelled()) { throw new IOException("Fail to execute request due to canceling"); } mConsumer.sign(request); if (BreadcrumbsAdapter.DEBUG) { Log.d(TAG, "Execute request: " + request.getURI()); for (Header header : request.getAllHeaders()) { Log.d(TAG, " with header: " + header.toString()); } } HttpResponse response = mHttpClient.execute(request); responseEntity = response.getEntity(); InputStream is = responseEntity.getContent(); InputStream stream = new BufferedInputStream(is, 8192); if (BreadcrumbsAdapter.DEBUG) { stream = XmlCreator.convertStreamToLoggedStream(TAG, stream); } XmlPullParserFactory factory = XmlPullParserFactory.newInstance(); factory.setNamespaceAware(true); XmlPullParser xpp = factory.newPullParser(); xpp.setInput(stream, "UTF-8"); String tagName = null; int eventType = xpp.getEventType(); String activityName = null; Integer activityId = null; while (eventType != XmlPullParser.END_DOCUMENT) { if (eventType == XmlPullParser.START_TAG) { tagName = xpp.getName(); } else if (eventType == XmlPullParser.END_TAG) { if ("activity".equals(xpp.getName()) && activityId != null && activityName != null) { mActivities.add(new Pair<Integer, String>(activityId, activityName)); } tagName = null; } else if (eventType == XmlPullParser.TEXT) { if ("id".equals(tagName)) { activityId = Integer.parseInt(xpp.getText()); } else if ("name".equals(tagName)) { activityName = xpp.getText(); } } eventType = xpp.next(); } } catch (OAuthMessageSignerException e) { mService.removeAuthentication(); handleError(mContext.getString(R.string.taskerror_breadcrumbs_activity), e, "Failed to sign the request with authentication signature"); } catch (OAuthExpectationFailedException e) { mService.removeAuthentication(); handleError(mContext.getString(R.string.taskerror_breadcrumbs_activity), e, "The request did not authenticate"); } catch (OAuthCommunicationException e) { mService.removeAuthentication(); handleError(mContext.getString(R.string.taskerror_breadcrumbs_activity), e, "The authentication communication failed"); } catch (IOException e) { handleError(mContext.getString(R.string.taskerror_breadcrumbs_activity), e, "A problem during communication"); } catch (XmlPullParserException e) { handleError(mContext.getString(R.string.taskerror_breadcrumbs_activity), e, "A problem while reading the XML data"); } finally { if (responseEntity != null) { try { //EntityUtils.consume(responseEntity); responseEntity.consumeContent(); } catch (IOException e) { Log.e(TAG, "Failed to close the content stream", e); } } } return null; }
From source file:com.clarionmedia.infinitum.http.rest.impl.CachingEnabledRestfulClient.java
private RestResponse executeRequest(HashableHttpRequest hashableHttpRequest) { if (mIsAuthenticated) mAuthStrategy.authenticate(hashableHttpRequest); if (mResponseCache.containsKey(hashableHttpRequest)) { RestResponse cachedResponse = mResponseCache.get(hashableHttpRequest); if (cachedResponse != null) return cachedResponse; }/* www .j a v a 2 s . co m*/ HttpUriRequest httpRequest = hashableHttpRequest.unwrap(); mLogger.debug("Sending " + httpRequest.getMethod() + " request to " + httpRequest.getURI() + " with " + httpRequest.getAllHeaders().length + " headers"); HttpClient httpClient = new DefaultHttpClient(mHttpParams); try { HttpResponse response = httpClient.execute(httpRequest); RestResponse restResponse = new RestResponse(response); StatusLine statusLine = response.getStatusLine(); restResponse.setStatusCode(statusLine.getStatusCode()); HttpEntity entity = response.getEntity(); if (entity == null) { restResponse.setResponseData(new byte[] {}); } else { ByteArrayOutputStream out = new ByteArrayOutputStream(); entity.writeTo(out); out.close(); restResponse.setResponseData(out.toByteArray()); } long expiration = getResponseExpiration(restResponse); if (expiration > 0) mResponseCache.put(hashableHttpRequest, restResponse, expiration); return restResponse; } catch (ClientProtocolException e) { mLogger.error("Unable to send " + httpRequest.getMethod() + " request", e); return null; } catch (IOException e) { mLogger.error("Unable to read web service response", e); return null; } }
From source file:org.everit.authentication.cas.ecm.tests.SampleApp.java
/** * Call session logout URL./*w ww.j av a 2 s .c om*/ */ public void sessionLogout(final SecureHttpClient secureHttpClient) throws Exception { CloseableHttpClient httpClient = secureHttpClient.getHttpClient(); HttpClientContext httpClientContext = secureHttpClient.getHttpClientContext(); HttpGet httpGet = new HttpGet(sessionLogoutUrl); HttpResponse httpResponse = httpClient.execute(httpGet, httpClientContext); Assert.assertEquals("URL should not be accessed [" + sessionLogoutUrl + "]", HttpServletResponse.SC_NOT_FOUND, httpResponse.getStatusLine().getStatusCode()); HttpUriRequest currentReq = (HttpUriRequest) httpClientContext.getRequest(); HttpHost currentHost = httpClientContext.getTargetHost(); String currentUrl = (currentReq.getURI().isAbsolute()) ? currentReq.getURI().toString() : (currentHost.toURI() + currentReq.getURI()); Assert.assertEquals(loggedOutUrl, currentUrl); EntityUtils.consume(httpResponse.getEntity()); }
From source file:pl.openrnd.connection.rest.ConnectionHandler.java
/** * Handles provided request and returns response related to it. * * The method creates a log if logging mechanism is enabled. * * Request is executed in a caller thread. * * @param request Request object//from www . j a v a 2 s. c o m * @return Response object */ public Response handleRequest(Request request) { Response result = null; int requestNumber = mRequestCounter++; Timer timer = null; HttpEntity httpEntity = null; InputStream inputStream = null; RestConnectionLog.Builder builder = null; if (mConnectionLogger.areLogsEnabled()) { builder = new RestConnectionLog.Builder(); builder.request(request); } Log.d(TAG, String.format("handleRequest(%d): ---> [%s]", requestNumber, request.getClass().getSimpleName())); try { HttpUriRequest httpUriRequest = request.getHttpUriRequest(); Log.d(TAG, String.format("handleRequest(%d): uri[%s]", requestNumber, httpUriRequest.getURI().toString())); logHeaders(requestNumber, httpUriRequest.getAllHeaders()); HttpResponse httpResponse; timer = startRequestTimer(request); if (builder != null) { builder.request(httpUriRequest); httpResponse = execute(httpUriRequest, request.getConnectionTimeout(), request.getReadTimeout()); builder.response(httpResponse); } else { httpResponse = execute(httpUriRequest, request.getConnectionTimeout(), request.getReadTimeout()); } stopRequestTimer(timer); int statusCode = httpResponse.getStatusLine().getStatusCode(); String reasonPhrase = httpResponse.getStatusLine().getReasonPhrase(); Log.d(TAG, String.format("handleRequest(%d): http response[%d / %s]", requestNumber, statusCode, reasonPhrase)); logHeaders(requestNumber, httpResponse.getAllHeaders()); httpEntity = httpResponse.getEntity(); inputStream = httpEntity.getContent(); boolean isStatusCodeSupported = request.supportsAllStatusCodes(); if (!isStatusCodeSupported) { int[] supportedStatusCodes = request.getSupportedStatusCodes(); for (int supportedStatusCode : supportedStatusCodes) { if (statusCode == supportedStatusCode) { isStatusCodeSupported = true; break; } } } if (isStatusCodeSupported) { result = request.getResponse(statusCode, reasonPhrase, httpResponse.getAllHeaders(), inputStream); } else { throw new UnsupportedResponseException(statusCode, reasonPhrase, httpResponse.getAllHeaders(), inputStream); } } catch (Exception exc) { Log.e(TAG, String.format("handleRequest(%d): ", requestNumber), exc); stopRequestTimer(timer); result = request.getResponse(exc); } finally { if (httpEntity != null) { try { httpEntity.consumeContent(); } catch (Exception exc) { Log.e(TAG, String.format("handleRequest(%d): ", requestNumber), exc); } } if (inputStream != null) { try { inputStream.close(); } catch (Exception exc) { Log.e(TAG, String.format("handleRequest(%d): ", requestNumber), exc); } } } if (builder != null) { builder.cookies(mCookieStore); builder.response(result); mConnectionLogger.addConnectionLog(builder.build()); } Log.d(TAG, String.format("handleRequest(%d): <---", requestNumber)); return result; }
From source file:wuit.crawler.CrawlerHtml.java
public String doGetHttp(String url) { HttpParams params = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(params, 12000); HttpConnectionParams.setSoTimeout(params, 9000); HttpClient httpclient = new DefaultHttpClient(params); String rs = ""; try {//from w ww. j av a 2 s . c om HttpGet httpget = new HttpGet(url); System.out.println("executing request " + url); HttpContext httpContext = new BasicHttpContext(); // httpget.addHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)"); httpget.addHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; QQDownload 1.7; .NET CLR 1.1.4322; CIBA; .NET CLR 2.0.50727)"); HttpResponse response = httpclient.execute(httpget, httpContext); HttpUriRequest realRequest = (HttpUriRequest) httpContext.getAttribute(ExecutionContext.HTTP_REQUEST); HttpHost targetHost = (HttpHost) httpContext.getAttribute(ExecutionContext.HTTP_TARGET_HOST); url = targetHost.toString() + realRequest.getURI(); int resStatu = response.getStatusLine().getStatusCode();//? if (resStatu == 200) { HttpEntity entity = response.getEntity(); if (entity != null) { rs = EntityUtils.toString(entity, "iso-8859-1"); String in_code = getEncoding(rs); String encode = getHtmlEncode(rs); if (encode.isEmpty()) { httpclient.getConnectionManager().shutdown(); return ""; } else { if (!in_code.toLowerCase().equals("utf-8") && !in_code.toLowerCase().equals(encode.toLowerCase())) { if (!in_code.toLowerCase().equals("iso-8859-1")) rs = new String(rs.getBytes("iso-8859-1"), in_code); if (!encode.toLowerCase().equals(in_code.toLowerCase())) rs = new String(rs.getBytes(in_code), encode); } } try { } catch (RuntimeException ex) { httpget.abort(); throw ex; } finally { // Closing the input stream will trigger connection release // try { instream.close(); } catch (Exception ignore) {} } } } } finally { // When HttpClient instance is no longer needed, // shut down the connection manager to ensure // immediate deallocation of all system resources httpclient.getConnectionManager().shutdown(); return rs; } }
From source file:org.callimachusproject.client.HttpClientFactoryTest.java
@Test public void test302CachedRedirectTarget() throws Exception { do {//from w ww. j av a 2 s .c om HttpGet get = new HttpGet("http://example.com/302"); get.getParams().setBooleanParameter(ClientPNames.HANDLE_REDIRECTS, true); BasicHttpResponse redirect = new BasicHttpResponse(_302); redirect.setHeader("Location", "http://example.com/200"); redirect.setHeader("Cache-Control", "public,max-age=3600"); responses.add(redirect); BasicHttpResponse doc = new BasicHttpResponse(_200); doc.setHeader("Cache-Control", "public,max-age=3600"); responses.add(doc); client.execute(get, new ResponseHandler<Void>() { public Void handleResponse(HttpResponse response) throws ClientProtocolException, IOException { assertEquals(_200.getStatusCode(), response.getStatusLine().getStatusCode()); return null; } }); } while (false); do { HttpContext localContext = new BasicHttpContext(); HttpGet get = new HttpGet("http://example.com/302"); get.getParams().setBooleanParameter(ClientPNames.HANDLE_REDIRECTS, false); BasicHttpResponse redirect = new BasicHttpResponse(_302); redirect.setHeader("Location", "http://example.com/200"); redirect.setHeader("Cache-Control", "public,max-age=3600"); responses.add(redirect); client.execute(get, new ResponseHandler<Void>() { public Void handleResponse(HttpResponse response) throws ClientProtocolException, IOException { assertEquals(_302.getStatusCode(), response.getStatusLine().getStatusCode()); return null; } }, localContext); HttpHost host = (HttpHost) localContext.getAttribute(ExecutionContext.HTTP_TARGET_HOST); HttpUriRequest req = (HttpUriRequest) localContext.getAttribute(ExecutionContext.HTTP_REQUEST); URI root = new URI(host.getSchemeName(), null, host.getHostName(), -1, "/", null, null); assertEquals("http://example.com/302", root.resolve(req.getURI()).toASCIIString()); } while (false); }
From source file:com.mutu.gpstracker.breadcrumbs.GetBreadcrumbsBundlesTask.java
/** * Retrieve the OAuth Request Token and present a browser to the user to * authorize the token./* ww w. j a va2 s . com*/ */ @Override protected Void doInBackground(Void... params) { HttpEntity responseEntity = null; mBundleIds = new HashSet<Integer>(); mBundles = new LinkedList<Object[]>(); try { HttpUriRequest request = new HttpGet("http://api.gobreadcrumbs.com/v1/bundles.xml"); if (isCancelled()) { throw new IOException("Fail to execute request due to canceling"); } mConsumer.sign(request); if (BreadcrumbsAdapter.DEBUG) { Log.d(TAG, "Execute request: " + request.getURI()); for (Header header : request.getAllHeaders()) { Log.d(TAG, " with header: " + header.toString()); } } HttpResponse response = mHttpclient.execute(request); responseEntity = response.getEntity(); InputStream is = responseEntity.getContent(); InputStream stream = new BufferedInputStream(is, 8192); if (BreadcrumbsAdapter.DEBUG) { stream = XmlCreator.convertStreamToLoggedStream(TAG, stream); } XmlPullParserFactory factory = XmlPullParserFactory.newInstance(); factory.setNamespaceAware(true); XmlPullParser xpp = factory.newPullParser(); xpp.setInput(stream, "UTF-8"); String tagName = null; int eventType = xpp.getEventType(); String bundleName = null, bundleDescription = null; Integer bundleId = null; while (eventType != XmlPullParser.END_DOCUMENT) { if (eventType == XmlPullParser.START_TAG) { tagName = xpp.getName(); } else if (eventType == XmlPullParser.END_TAG) { if ("bundle".equals(xpp.getName()) && bundleId != null) { mBundles.add(new Object[] { bundleId, bundleName, bundleDescription }); } tagName = null; } else if (eventType == XmlPullParser.TEXT) { if ("description".equals(tagName)) { bundleDescription = xpp.getText(); } else if ("id".equals(tagName)) { bundleId = Integer.parseInt(xpp.getText()); mBundleIds.add(bundleId); } else if ("name".equals(tagName)) { bundleName = xpp.getText(); } } eventType = xpp.next(); } } catch (OAuthMessageSignerException e) { mService.removeAuthentication(); handleError(mContext.getString(R.string.taskerror_breadcrumbs_bundle), e, "Failed to sign the request with authentication signature"); } catch (OAuthExpectationFailedException e) { mService.removeAuthentication(); handleError(mContext.getString(R.string.taskerror_breadcrumbs_bundle), e, "The request did not authenticate"); } catch (OAuthCommunicationException e) { mService.removeAuthentication(); handleError(mContext.getString(R.string.taskerror_breadcrumbs_bundle), e, "The authentication communication failed"); } catch (IOException e) { handleError(mContext.getString(R.string.taskerror_breadcrumbs_bundle), e, "A problem during communication"); } catch (XmlPullParserException e) { handleError(mContext.getString(R.string.taskerror_breadcrumbs_bundle), e, "A problem while reading the XML data"); } catch (IllegalStateException e) { handleError(mContext.getString(R.string.taskerror_breadcrumbs_bundle), e, "A problem during communication"); } finally { if (responseEntity != null) { try { //EntityUtils.consume(responseEntity); responseEntity.consumeContent(); } catch (IOException e) { Log.w(TAG, "Failed closing inputstream"); } } } return null; }
From source file:org.sonatype.nexus.proxy.storage.remote.httpclient.HttpClientRemoteStorage.java
/** * Executes the HTTP request.// w w w .j ava2s . co m * <p/> * In case of any exception thrown by HttpClient, it will release the connection. In other cases it * is the duty of caller to do it, or process the input stream. * * @param repository to execute the HTTP method fpr * @param request resource store request that triggered the HTTP request * @param httpRequest HTTP request to be executed * @return response of making the request * @throws RemoteStorageException If an error occurred during execution of HTTP request */ private HttpResponse executeRequest(final ProxyRepository repository, final ResourceStoreRequest request, final HttpUriRequest httpRequest) throws RemoteStorageException { final URI methodUri = httpRequest.getURI(); if (getLogger().isDebugEnabled()) { getLogger().debug( "Invoking HTTP " + httpRequest.getMethod() + " method against remote location " + methodUri); } final RemoteStorageContext ctx = getRemoteStorageContext(repository); final HttpClient httpClient = HttpClientUtil.getHttpClient(CTX_KEY, ctx); httpRequest.setHeader("user-agent", formatUserAgentString(ctx, repository)); httpRequest.setHeader("accept", "*/*"); httpRequest.setHeader("accept-language", "en-us"); httpRequest.setHeader("accept-encoding", "gzip,deflate,identity"); httpRequest.setHeader("cache-control", "no-cache"); // HTTP keep alive should not be used, except when NTLM is used final Boolean isNtlmUsed = HttpClientUtil.isNTLMAuthenticationUsed(CTX_KEY, ctx); if (isNtlmUsed == null || !isNtlmUsed) { httpRequest.setHeader("Connection", "close"); httpRequest.setHeader("Proxy-Connection", "close"); } HttpResponse httpResponse = null; try { httpResponse = httpClient.execute(httpRequest); final int statusCode = httpResponse.getStatusLine().getStatusCode(); final Header httpServerHeader = httpResponse.getFirstHeader("server"); checkForRemotePeerAmazonS3Storage(repository, httpServerHeader == null ? null : httpServerHeader.getValue()); Header proxyReturnedErrorHeader = httpResponse.getFirstHeader(NEXUS_MISSING_ARTIFACT_HEADER); boolean proxyReturnedError = proxyReturnedErrorHeader != null && Boolean.valueOf(proxyReturnedErrorHeader.getValue()); if (statusCode == HttpStatus.SC_FORBIDDEN) { throw new RemoteAccessDeniedException(repository, methodUri.toASCIIString(), httpResponse.getStatusLine().getReasonPhrase()); } else if (statusCode == HttpStatus.SC_UNAUTHORIZED) { throw new RemoteAuthenticationNeededException(repository, httpResponse.getStatusLine().getReasonPhrase()); } else if (statusCode == HttpStatus.SC_OK && proxyReturnedError) { throw new RemoteStorageException( "Invalid artifact found, most likely a proxy redirected to an HTML error page."); } return httpResponse; } catch (RemoteStorageException ex) { release(httpResponse); throw ex; } catch (ClientProtocolException ex) { release(httpResponse); throw new RemoteStorageException("Protocol error while executing " + httpRequest.getMethod() + " method. [repositoryId=\"" + repository.getId() + "\", requestPath=\"" + request.getRequestPath() + "\", remoteUrl=\"" + methodUri.toASCIIString() + "\"]", ex); } catch (IOException ex) { release(httpResponse); throw new RemoteStorageException("Transport error while executing " + httpRequest.getMethod() + " method [repositoryId=\"" + repository.getId() + "\", requestPath=\"" + request.getRequestPath() + "\", remoteUrl=\"" + methodUri.toASCIIString() + "\"]", ex); } }