List of usage examples for org.apache.http.client.methods HttpHead HttpHead
public HttpHead(final String uri)
From source file:eu.delving.sip.files.LinkChecker.java
private LinkCheck linkCheckRequest(String url) throws IOException { HttpHead head = new HttpHead(url); HttpResponse response = httpClient.execute(head); StatusLine status = response.getStatusLine(); if (status.getStatusCode() == HttpStatus.SC_INTERNAL_SERVER_ERROR) { HttpGet get = new HttpGet(url); response = httpClient.execute(get); status = response.getStatusLine(); }// ww w. j av a 2s . c o m LinkCheck linkCheck = new LinkCheck(); linkCheck.httpStatus = status.getStatusCode(); linkCheck.time = System.currentTimeMillis(); Header contentType = response.getLastHeader("Content-Type"); linkCheck.mimeType = contentType == null ? null : contentType.getValue(); Header contentLength = response.getLastHeader("Content-Length"); linkCheck.fileSize = contentLength == null ? -1 : Integer.parseInt(contentLength.getValue()); linkCheck.ok = linkCheck.httpStatus == HttpStatus.SC_OK; EntityUtils.consume(response.getEntity()); return linkCheck; }
From source file:com.google.step2.http.DefaultHttpFetcher.java
public FetchResponse fetch(FetchRequest request) throws FetchException { HttpUriRequest uriRequest;//w w w. j a v a 2 s .c o m switch (request.getMethod()) { case GET: uriRequest = new HttpGet(request.getUri()); break; case POST: uriRequest = new HttpPost(request.getUri()); break; case HEAD: uriRequest = new HttpHead(request.getUri()); break; default: throw new FetchException("unsupported HTTP method: " + request.getMethod()); } try { return new DefaultFetchResponse(httpClient.execute(uriRequest)); } catch (ClientProtocolException e) { throw new FetchException(request, e); } catch (IOException e) { throw new FetchException(request, e); } }
From source file:com.android.browser.kai.FetchUrlMimeType.java
@Override public String doInBackground(ContentValues... values) { mValues = values[0];/* w ww . java 2s. c om*/ // Check to make sure we have a URI to download String uri = mValues.getAsString(Downloads.COLUMN_URI); if (uri == null || uri.length() == 0) { return null; } // User agent is likely to be null, though the AndroidHttpClient // seems ok with that. AndroidHttpClient client = AndroidHttpClient.newInstance(mValues.getAsString(Downloads.COLUMN_USER_AGENT)); HttpHead request = new HttpHead(uri); String cookie = mValues.getAsString(Downloads.COLUMN_COOKIE_DATA); if (cookie != null && cookie.length() > 0) { request.addHeader("Cookie", cookie); } String referer = mValues.getAsString(Downloads.COLUMN_REFERER); if (referer != null && referer.length() > 0) { request.addHeader("Referer", referer); } HttpResponse response; String mimeType = null; try { response = client.execute(request); // We could get a redirect here, but if we do lets let // the download manager take care of it, and thus trust that // the server sends the right mimetype if (response.getStatusLine().getStatusCode() == 200) { Header header = response.getFirstHeader("Content-Type"); if (header != null) { mimeType = header.getValue(); final int semicolonIndex = mimeType.indexOf(';'); if (semicolonIndex != -1) { mimeType = mimeType.substring(0, semicolonIndex); } } } } catch (IllegalArgumentException ex) { request.abort(); } catch (IOException ex) { request.abort(); } finally { client.close(); } return mimeType; }
From source file:com.android.xbrowser.FetchUrlMimeType.java
@Override public void run() { // User agent is likely to be null, though the AndroidHttpClient // seems ok with that. AndroidHttpClient client = AndroidHttpClient.newInstance(mUserAgent); HttpHost httpHost = Proxy.getPreferredHttpHost(mContext, mUri); if (httpHost != null) { ConnRouteParams.setDefaultProxy(client.getParams(), httpHost); }//from w ww . j av a 2 s . c om HttpHead request = new HttpHead(mUri); if (mCookies != null && mCookies.length() > 0) { request.addHeader("Cookie", mCookies); } HttpResponse response; String mimeType = null; String contentDisposition = null; try { response = client.execute(request); // We could get a redirect here, but if we do lets let // the download manager take care of it, and thus trust that // the server sends the right mimetype if (response.getStatusLine().getStatusCode() == 200) { Header header = response.getFirstHeader("Content-Type"); if (header != null) { mimeType = header.getValue(); final int semicolonIndex = mimeType.indexOf(';'); if (semicolonIndex != -1) { mimeType = mimeType.substring(0, semicolonIndex); } } Header contentDispositionHeader = response.getFirstHeader("Content-Disposition"); if (contentDispositionHeader != null) { contentDisposition = contentDispositionHeader.getValue(); } } } catch (IllegalArgumentException ex) { request.abort(); } catch (IOException ex) { request.abort(); } finally { client.close(); } if (mimeType != null) { if (mimeType.equalsIgnoreCase("text/plain") || mimeType.equalsIgnoreCase("application/octet-stream")) { String newMimeType = MimeTypeMap.getSingleton() .getMimeTypeFromExtension(MimeTypeMap.getFileExtensionFromUrl(mUri)); if (newMimeType != null) { mRequest.setMimeType(newMimeType); } } String filename = URLUtil.guessFileName(mUri, contentDisposition, mimeType); mRequest.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, filename); } // Start the download DownloadManager manager = (DownloadManager) mContext.getSystemService(Context.DOWNLOAD_SERVICE); manager.enqueue(mRequest); }
From source file:com.android.browser.FetchUrlMimeType.java
@Override public ContentValues doInBackground(ContentValues... values) { mValues = values[0];// w ww . j a v a2 s . co m // Check to make sure we have a URI to download String uri = mValues.getAsString(Downloads.Impl.COLUMN_URI); if (uri == null || uri.length() == 0) { return null; } // User agent is likely to be null, though the AndroidHttpClient // seems ok with that. AndroidHttpClient client = AndroidHttpClient .newInstance(mValues.getAsString(Downloads.Impl.COLUMN_USER_AGENT)); HttpHead request = new HttpHead(uri); String cookie = mValues.getAsString(Downloads.Impl.COLUMN_COOKIE_DATA); if (cookie != null && cookie.length() > 0) { request.addHeader("Cookie", cookie); } String referer = mValues.getAsString(Downloads.Impl.COLUMN_REFERER); if (referer != null && referer.length() > 0) { request.addHeader("Referer", referer); } HttpResponse response; ContentValues result = new ContentValues(); try { response = client.execute(request); // We could get a redirect here, but if we do lets let // the download manager take care of it, and thus trust that // the server sends the right mimetype if (response.getStatusLine().getStatusCode() == 200) { Header header = response.getFirstHeader("Content-Type"); if (header != null) { String mimeType = header.getValue(); final int semicolonIndex = mimeType.indexOf(';'); if (semicolonIndex != -1) { mimeType = mimeType.substring(0, semicolonIndex); } result.put("Content-Type", mimeType); } Header contentDispositionHeader = response.getFirstHeader("Content-Disposition"); if (contentDispositionHeader != null) { result.put("Content-Disposition", contentDispositionHeader.getValue()); } } } catch (IllegalArgumentException ex) { request.abort(); } catch (IOException ex) { request.abort(); } finally { client.close(); } return result; }
From source file:tech.beshu.ror.integration.FiltersAndFieldsSecurityTests.java
private static void insertDoc(String docName, RestClient restClient, String idx, String field) { if (adminClient == null) { adminClient = restClient;/* w ww. j a v a 2s . co m*/ } String path = "/" + IDX_PREFIX + idx + "/documents/doc-" + docName + String.valueOf(Math.random()); try { HttpPut request = new HttpPut(restClient.from(path)); request.setHeader("Content-Type", "application/json"); request.setHeader("refresh", "true"); request.setHeader("timeout", "50s"); request.setEntity(new StringEntity("{\"" + field + "\": \"" + docName + "\", \"dummy\": true}")); System.out.println(body(restClient.execute(request))); } catch (Exception e) { e.printStackTrace(); throw new IllegalStateException("Test problem", e); } // Polling phase.. #TODO is there a better way? try { HttpResponse response; do { HttpHead request = new HttpHead(restClient.from(path)); request.setHeader("x-api-key", "p"); response = restClient.execute(request); System.out.println( "polling for " + docName + ".. result: " + response.getStatusLine().getReasonPhrase()); Thread.sleep(200); } while (response.getStatusLine().getStatusCode() != 200); } catch (Exception e) { e.printStackTrace(); throw new IllegalStateException("Cannot configure test case", e); } }
From source file:com.github.technosf.posterer.transports.commons.CommonsResponseModelTaskImpl.java
/** * @param uri//from w w w . ja v a 2s. com * @param method * @return */ private static HttpUriRequest createRequest(URI uri, String method) { switch (method) { case "GET": return new HttpGet(uri); case "HEAD": return new HttpHead(uri); case "POST": return new HttpPost(uri); case "PUT": return new HttpPut(uri); case "DELETE": return new HttpDelete(uri); case "TRACE": return new HttpTrace(uri); case "OPTIONS": return new HttpOptions(uri); case "PATCH": return new HttpPatch(uri); } return null; }
From source file:tv.arte.resteventapi.core.clients.RestEventApiRestClient.java
/** * Executes the REST request described by the {@link RestEvent} * /*from www. ja v a2s. c o m*/ * @param restEvent The {@link RestEvent} to process * @return A result of the execution * @throws RestEventApiRuntimeException In case of non managed errors */ public static RestClientExecutionResult execute(final RestEvent restEvent) throws RestEventApiRuntimeException { RestClientExecutionResult result = new RestClientExecutionResult(); String url = restEvent.getUrl(); CloseableHttpClient client = null; HttpUriRequest request = null; Integer responseCode = null; try { //Request custom configs RequestConfig.Builder requestBuilder = RequestConfig.custom(); requestBuilder = requestBuilder.setConnectTimeout(restEvent.getTimeout()); requestBuilder = requestBuilder.setConnectionRequestTimeout(restEvent.getTimeout()); client = HttpClientBuilder.create().setDefaultRequestConfig(requestBuilder.build()).build(); //Determine the method to execute switch (restEvent.getMethod()) { case GET: request = new HttpGet(url); break; case POST: request = new HttpPost(url); break; case PUT: request = new HttpPut(url); break; case DELETE: request = new HttpDelete(url); break; case PATCH: request = new HttpPatch(url); break; case HEAD: request = new HttpHead(url); break; default: throw new RestEventApiRuntimeException("RestEventAPI unsupported HTTP method"); } //Set the body for eligible methods if (restEvent.getBody() != null && request instanceof HttpEntityEnclosingRequestBase) { ((HttpEntityEnclosingRequestBase) request).setEntity(new StringEntity(restEvent.getBody())); } //Set headers if (CollectionUtils.isNotEmpty(restEvent.getHeaders())) { for (String strHeader : restEvent.getHeaders()) { CharArrayBuffer headerBuffer = new CharArrayBuffer(strHeader.length() + 1); headerBuffer.append(strHeader); request.addHeader(new BufferedHeader(headerBuffer)); } } HttpResponse response = client.execute(request); responseCode = response.getStatusLine().getStatusCode(); result.setState(RestClientCallState.OK); } catch (ConnectTimeoutException e) { result.setState(RestClientCallState.TIMEOUT); } catch (Exception e) { throw new RestEventApiRuntimeException("Un error occured while processing rest event", e); } finally { result.setResponseCode(responseCode); try { client.close(); } catch (Exception e2) { logger.warn("Unable to close HTTP client", e2); } } return result; }
From source file:com.dajodi.scandic.ScandicSessionHelper.java
private static void login(String username, String password) throws Exception { DefaultHttpClient client = Singleton.INSTANCE.getHttpClient(); client.getCookieStore().clear();//from w w w .ja v a2 s . co m HttpHead head = new HttpHead("https://www.scandichotels.com/Frequent-Guest-Programme/"); // only for user-agent Util.gzipify(head); HttpResponse response = client.execute(head); if (response.getStatusLine().getStatusCode() != 200) { throw new ScandicHtmlException("HEAD request to FG page did not return a 200, instead " + response.getStatusLine().getStatusCode()); } head.abort(); boolean found = false; // assume this cookie exists for (Cookie cookie : client.getCookieStore().getCookies()) { if (SESSION_ID_COOKIE_NAME.equals(cookie.getName())) { found = true; break; } } if (!found) { throw new ScandicHtmlException("Session id cookie not valid from head request, dying"); } List<NameValuePair> nvps = new LinkedList<NameValuePair>(); nvps.add(new BasicNameValuePair("ctl00$MenuLoginStatus$txtLoyaltyUsername", username)); nvps.add(new BasicNameValuePair("ctl00$MenuLoginStatus$txtLoyaltyPassword", password)); nvps.add(new BasicNameValuePair("ctl00$MenuLoginStatus$loginPopUpID", "LOGIN_POPUP_MODULE")); nvps.add(new BasicNameValuePair("ctl00$MenuLoginStatus$loginPopUpPageID", "LOGIN_POPUP_MODULE")); nvps.add(new BasicNameValuePair("__PREVIOUSPAGE", "")); nvps.add(new BasicNameValuePair("__EVENTTARGET", "ctl00$MenuLoginStatus$btnLogIn")); UrlEncodedFormEntity entity = new UrlEncodedFormEntity(nvps); // now the post HttpPost post = new HttpPost("https://www.scandichotels.com/templates/Booking/Units/LoginValidator.aspx"); post.setHeader("Content-Type", "application/x-www-form-urlencoded"); // needed, we don't want redirecting here final HttpParams params = new BasicHttpParams(); HttpClientParams.setRedirecting(params, false); post.setParams(params); // not really needed, but why not Util.gzipify(post); post.setEntity(entity); response = client.execute(post); post.abort(); if (isLoggedIn()) { Log.d("Success! Logged in via Java code!"); } else if (response.getStatusLine().getStatusCode() == 302 && response.getFirstHeader("Location").getValue().contains("Login-Error")) { throw new InvalidLoginException(); } else { throw new RuntimeException("Could not login!"); } }