List of usage examples for org.apache.http.client.methods HttpHead HttpHead
public HttpHead(final String uri)
From source file:uk.co.unclealex.googleauth.ApacheHttpTransport.java
@Override public ApacheHttpRequest buildHeadRequest(String url) { return new ApacheHttpRequest(httpClient, new HttpHead(mangle(url))); }
From source file:com.mobiperf.measurements.HttpTask.java
/** Runs the HTTP measurement task. Will acquire power lock to ensure wifi is not turned off */ @Override//from ww w . j a va 2s . c om public MeasurementResult call() throws MeasurementError { int statusCode = HttpTask.DEFAULT_STATUS_CODE; long duration = 0; long originalHeadersLen = 0; long originalBodyLen; String headers = null; ByteBuffer body = ByteBuffer.allocate(HttpTask.MAX_BODY_SIZE_TO_UPLOAD); boolean success = false; String errorMsg = ""; InputStream inputStream = null; // This is not the ideal way of doing things, as we can pick up data // from other processes and be overly cautious in running measurements. // However, taking the packet sizes is completely inaccurate, and it's hard to // come up with a consistent expected value, unlike with DNS RRCTask.PacketMonitor packetmonitor = new RRCTask.PacketMonitor(); packetmonitor.setBySize(); packetmonitor.readCurrentPacketValues(); try { // set the download URL, a URL that points to a file on the Internet // this is the file to be downloaded HttpDesc task = (HttpDesc) this.measurementDesc; String urlStr = task.url; // TODO(Wenjie): Need to set timeout for the HTTP methods httpClient = AndroidHttpClient.newInstance(Util.prepareUserAgent(this.parent)); HttpRequestBase request = null; if (task.method.compareToIgnoreCase("head") == 0) { request = new HttpHead(urlStr); } else if (task.method.compareToIgnoreCase("get") == 0) { request = new HttpGet(urlStr); } else if (task.method.compareToIgnoreCase("post") == 0) { request = new HttpPost(urlStr); HttpPost postRequest = (HttpPost) request; postRequest.setEntity(new StringEntity(task.body)); } else { // Use GET by default request = new HttpGet(urlStr); } if (task.headers != null && task.headers.trim().length() > 0) { for (String headerLine : task.headers.split("\r\n")) { String tokens[] = headerLine.split(":"); if (tokens.length == 2) { request.addHeader(tokens[0], tokens[1]); } else { throw new MeasurementError("Incorrect header line: " + headerLine); } } } byte[] readBuffer = new byte[HttpTask.READ_BUFFER_SIZE]; int readLen; int totalBodyLen = 0; long startTime = System.currentTimeMillis(); HttpResponse response = httpClient.execute(request); /* TODO(Wenjie): HttpClient does not automatically handle the following codes * 301 Moved Permanently. HttpStatus.SC_MOVED_PERMANENTLY * 302 Moved Temporarily. HttpStatus.SC_MOVED_TEMPORARILY * 303 See Other. HttpStatus.SC_SEE_OTHER * 307 Temporary Redirect. HttpStatus.SC_TEMPORARY_REDIRECT * * We may want to fetch instead from the redirected page. */ StatusLine statusLine = response.getStatusLine(); if (statusLine != null) { statusCode = statusLine.getStatusCode(); success = (statusCode == 200); } /* For HttpClient to work properly, we still want to consume the entire response even if * the status code is not 200 */ HttpEntity responseEntity = response.getEntity(); originalBodyLen = responseEntity.getContentLength(); long expectedResponseLen = HttpTask.MAX_HTTP_RESPONSE_SIZE; // getContentLength() returns negative number if body length is unknown if (originalBodyLen > 0) { expectedResponseLen = originalBodyLen; } if (responseEntity != null) { inputStream = responseEntity.getContent(); while ((readLen = inputStream.read(readBuffer)) > 0 && totalBodyLen <= HttpTask.MAX_HTTP_RESPONSE_SIZE) { totalBodyLen += readLen; // Fill in the body to report up to MAX_BODY_SIZE if (body.remaining() > 0) { int putLen = body.remaining() < readLen ? body.remaining() : readLen; body.put(readBuffer, 0, putLen); } this.progress = (int) (100 * totalBodyLen / expectedResponseLen); this.progress = Math.min(Config.MAX_PROGRESS_BAR_VALUE, progress); broadcastProgressForUser(this.progress); } duration = System.currentTimeMillis() - startTime; } Header[] responseHeaders = response.getAllHeaders(); if (responseHeaders != null) { headers = ""; for (Header hdr : responseHeaders) { /* * TODO(Wenjie): There can be preceding and trailing white spaces in * each header field. I cannot find internal methods that return the * number of bytes in a header. The solution here assumes the encoding * is one byte per character. */ originalHeadersLen += hdr.toString().length(); headers += hdr.toString() + "\r\n"; } } PhoneUtils phoneUtils = PhoneUtils.getPhoneUtils(); MeasurementResult result = new MeasurementResult(phoneUtils.getDeviceInfo().deviceId, phoneUtils.getDeviceProperty(), HttpTask.TYPE, System.currentTimeMillis() * 1000, success, this.measurementDesc); result.addResult("code", statusCode); dataConsumed = packetmonitor.getPacketsSentDiff(); if (success) { result.addResult("time_ms", duration); result.addResult("headers_len", originalHeadersLen); result.addResult("body_len", totalBodyLen); result.addResult("headers", headers); result.addResult("body", Base64.encodeToString(body.array(), Base64.DEFAULT)); } Logger.i(MeasurementJsonConvertor.toJsonString(result)); return result; } catch (MalformedURLException e) { errorMsg += e.getMessage() + "\n"; Logger.e(e.getMessage()); } catch (IOException e) { errorMsg += e.getMessage() + "\n"; Logger.e(e.getMessage()); } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { Logger.e("Fails to close the input stream from the HTTP response"); } } if (httpClient != null) { httpClient.close(); } } throw new MeasurementError("Cannot get result from HTTP measurement because " + errorMsg); }
From source file:net.paissad.waqtsalat.service.utils.HttpUtils.java
private static HttpRequestBase getNewHttpRequest(final String url, final RequestType requestType, final Header[] additionalRequestHeaders) { HttpRequestBase request = null;// w ww . j a v a 2 s.c om if (requestType == RequestType.HEAD) { request = new HttpHead(url); } else if (requestType == RequestType.GET) { request = new HttpGet(url); } else { throw new IllegalStateException("The 'RequestType' " + requestType + " is not supported yet !"); } request.addHeader("User-Agent", WSConstants.WS_USER_AGENT); if (additionalRequestHeaders != null && additionalRequestHeaders.length > 0) { for (Header aHeader : additionalRequestHeaders) { request.setHeader(aHeader); } } return request; }
From source file:org.apache.marmotta.ldclient.services.ldclient.LDClient.java
@Override public boolean ping(String resource) { //crappy implementation only for http if (resource.startsWith("http://") || resource.startsWith("https://")) { try {/*from www . jav a 2 s . c o m*/ return (200 == client.execute(new HttpHead(resource)).getStatusLine().getStatusCode()); } catch (Exception e) { log.error(e.getMessage()); return false; } } else { throw new UnsupportedOperationException("protocol not supportted"); } }
From source file:com.upyun.sdk.utils.HttpClientUtils.java
private static HttpResponse head(String url, HttpClient httpclient, Map<String, String> headers) { HttpHead httpHead = new HttpHead(url); HttpResponse response = null;/* w w w . ja v a 2 s . c o m*/ if (headers != null) { for (String key : headers.keySet()) { httpHead.addHeader(key, headers.get(key)); } } httpclient.getParams().setIntParameter(HttpConnectionParams.CONNECTION_TIMEOUT, CONNECTION_TIMEOUT);// httpclient.getParams().setIntParameter(HttpConnectionParams.SO_TIMEOUT, SO_TIMEOUT); // ? try { response = httpclient.execute(httpHead); } catch (Exception e) { LogUtil.exception(logger, e); } return response; }
From source file:com.google.code.jerseyclients.httpclientfour.ApacheHttpClientFourHandler.java
private HttpRequestBase getHttpMethod(ClientRequest cr) { final String strMethod = cr.getMethod(); final String uri = cr.getURI().toString(); if (strMethod.equals("GET")) { return new HttpGet(uri); } else if (strMethod.equals("POST")) { return new HttpPost(uri); } else if (strMethod.equals("PUT")) { return new HttpPut(uri); } else if (strMethod.equals("DELETE")) { return new HttpDelete(uri); } else if (strMethod.equals("HEAD")) { return new HttpHead(uri); } else if (strMethod.equals("OPTIONS")) { return new HttpOptions(uri); } else {// ww w. ja v a 2 s . c o m throw new ClientHandlerException("Method " + strMethod + " is not supported."); } }
From source file:org.jfrog.build.client.ArtifactoryDependenciesClient.java
private HttpResponse execute(String artifactUrl, boolean isHead) throws IOException { PreemptiveHttpClient client = httpClient.getHttpClient(); artifactUrl = ArtifactoryHttpClient.encodeUrl(artifactUrl); HttpRequestBase httpRequest = isHead ? new HttpHead(artifactUrl) : new HttpGet(artifactUrl); //Explicitly force keep alive httpRequest.setHeader("Connection", "Keep-Alive"); HttpResponse response = client.execute(httpRequest); StatusLine statusLine = response.getStatusLine(); int statusCode = statusLine.getStatusCode(); if (statusCode == HttpStatus.SC_NOT_FOUND) { EntityUtils.consume(response.getEntity()); throw new FileNotFoundException("Unable to find " + artifactUrl); }//from ww w . jav a2 s.com if (statusCode != HttpStatus.SC_OK) { EntityUtils.consume(response.getEntity()); throw new IOException("Error downloading " + artifactUrl + ". Code: " + statusCode + " Message: " + statusLine.getReasonPhrase()); } return response; }
From source file:org.elasticsearch.client.RequestLoggerTests.java
private static HttpUriRequest randomHttpRequest(URI uri) { int requestType = randomIntBetween(0, 7); switch (requestType) { case 0:// ww w . j av a 2 s . com return new HttpGetWithEntity(uri); case 1: return new HttpPost(uri); case 2: return new HttpPut(uri); case 3: return new HttpDeleteWithEntity(uri); case 4: return new HttpHead(uri); case 5: return new HttpTrace(uri); case 6: return new HttpOptions(uri); case 7: return new HttpPatch(uri); default: throw new UnsupportedOperationException(); } }