List of usage examples for org.apache.http.client.methods HttpHead HttpHead
public HttpHead(final String uri)
From source file:com.basho.riak.client.http.util.ClientHelper.java
/** * Same as {@link RiakClient}, except only returning the HTTP response *//*from w w w . j a v a 2s .c om*/ public HttpResponse fetchMeta(String bucket, String key, RequestMeta meta) { if (meta == null) { meta = new RequestMeta(); } HttpHead head = new HttpHead(ClientUtils.makeURI(config, bucket, key)); return executeMethod(bucket, key, head, meta); }
From source file:com.amos.tool.SelfRedirectStrategy.java
public HttpUriRequest getRedirect(final HttpRequest request, final HttpResponse response, final HttpContext context) throws ProtocolException { final URI uri = getLocationURI(request, response, context); final String method = request.getRequestLine().getMethod(); if (method.equalsIgnoreCase(HttpHead.METHOD_NAME)) { return new HttpHead(uri); } else if (method.equalsIgnoreCase(HttpGet.METHOD_NAME)) { return new HttpGet(uri); } else if (method.equalsIgnoreCase(HttpPost.METHOD_NAME)) { return new HttpPost(uri); } else {// ww w .j ava 2 s . c o m final int status = response.getStatusLine().getStatusCode(); if (status == HttpStatus.SC_TEMPORARY_REDIRECT) { return RequestBuilder.copy(request).setUri(uri).build(); } else { return new HttpGet(uri); } } }
From source file:self.philbrown.javaQuery.AjaxTask.java
@Override protected TaskResponse doInBackground(Void... arg0) { //handle cached responses CachedResponse cachedResponse = URLresponses .get(String.format(Locale.US, "%s_?=%s", options.url(), options.dataType())); //handle ajax caching option if (cachedResponse != null) { if (options.cache()) { if (new Date().getTime() - cachedResponse.timestamp.getTime() < options.cacheTimeout()) { //return cached response Success s = new Success(); s.obj = cachedResponse.response; s.reason = "cached response"; s.headers = null;/*from w w w . j a v a 2 s .c o m*/ return s; } } } if (request == null) { String type = options.type(); if (type == null) type = "GET"; if (type.equalsIgnoreCase("DELETE")) { request = new HttpDelete(options.url()); } else if (type.equalsIgnoreCase("GET")) { request = new HttpGet(options.url()); } else if (type.equalsIgnoreCase("HEAD")) { request = new HttpHead(options.url()); } else if (type.equalsIgnoreCase("OPTIONS")) { request = new HttpOptions(options.url()); } else if (type.equalsIgnoreCase("POST")) { request = new HttpPost(options.url()); } else if (type.equalsIgnoreCase("PUT")) { request = new HttpPut(options.url()); } else if (type.equalsIgnoreCase("TRACE")) { request = new HttpTrace(options.url()); } else if (type.equalsIgnoreCase("CUSTOM")) { try { request = options.customRequest(); } catch (Exception e) { request = null; } if (request == null) { Log.w("javaQuery.ajax", "CUSTOM type set, but AjaxOptions.customRequest is invalid. Defaulting to GET."); request = new HttpGet(); } } else { //default to GET request = new HttpGet(); } } Map<String, Object> args = new HashMap<String, Object>(); args.put("options", options); args.put("request", request); EventCenter.trigger("ajaxPrefilter", args, null); if (options.headers() != null) { if (options.headers().authorization() != null) { options.headers() .authorization(options.headers().authorization() + " " + options.getEncodedCredentials()); } else if (options.username() != null) { //guessing that authentication is basic options.headers().authorization("Basic " + options.getEncodedCredentials()); } for (Entry<String, String> entry : options.headers().map().entrySet()) { request.addHeader(entry.getKey(), entry.getValue()); } } if (options.data() != null) { try { Method setEntity = request.getClass().getMethod("setEntity", new Class<?>[] { HttpEntity.class }); if (options.processData() == null) { setEntity.invoke(request, new StringEntity(options.data().toString())); } else { Class<?> dataProcessor = Class.forName(options.processData()); Constructor<?> constructor = dataProcessor.getConstructor(new Class<?>[] { Object.class }); setEntity.invoke(request, constructor.newInstance(options.data())); } } catch (Throwable t) { Log.w("Ajax", "Could not post data"); } } HttpParams params = new BasicHttpParams(); if (options.timeout() != 0) { HttpConnectionParams.setConnectionTimeout(params, options.timeout()); HttpConnectionParams.setSoTimeout(params, options.timeout()); } HttpClient client = new DefaultHttpClient(params); HttpResponse response = null; try { if (options.cookies() != null) { CookieStore cookies = new BasicCookieStore(); for (Entry<String, String> entry : options.cookies().entrySet()) { cookies.addCookie(new BasicClientCookie(entry.getKey(), entry.getValue())); } HttpContext httpContext = new BasicHttpContext(); httpContext.setAttribute(ClientContext.COOKIE_STORE, cookies); response = client.execute(request, httpContext); } else { response = client.execute(request); } if (options.dataFilter() != null) { if (options.context() != null) options.dataFilter().invoke(new $(options.context()), response, options.dataType()); else options.dataFilter().invoke(null, response, options.dataType()); } StatusLine statusLine = response.getStatusLine(); Function function = options.statusCode().get(statusLine); if (function != null) { if (options.context() != null) function.invoke(new $(options.context())); else function.invoke(null); } if (statusLine.getStatusCode() >= 300) { //an error occurred Error e = new Error(); AjaxError error = new AjaxError(); error.request = request; error.options = options; e.status = statusLine.getStatusCode(); e.reason = statusLine.getReasonPhrase(); error.status = e.status; error.reason = e.reason; e.headers = response.getAllHeaders(); e.error = error; return e; } else { //handle dataType String dataType = options.dataType(); if (dataType == null) dataType = "text"; Object parsedResponse = null; boolean success = true; try { if (dataType.equalsIgnoreCase("text") || dataType.equalsIgnoreCase("html")) { parsedResponse = parseText(response); } else if (dataType.equalsIgnoreCase("xml")) { if (options.customXMLParser() != null) { InputStream is = response.getEntity().getContent(); if (options.SAXContentHandler() != null) options.customXMLParser().parse(is, options.SAXContentHandler()); else options.customXMLParser().parse(is, new DefaultHandler()); parsedResponse = "Response handled by custom SAX parser"; } else if (options.SAXContentHandler() != null) { InputStream is = response.getEntity().getContent(); SAXParserFactory factory = SAXParserFactory.newInstance(); factory.setFeature("http://xml.org/sax/features/namespaces", false); factory.setFeature("http://xml.org/sax/features/namespace-prefixes", true); SAXParser parser = factory.newSAXParser(); XMLReader reader = parser.getXMLReader(); reader.setContentHandler(options.SAXContentHandler()); reader.parse(new InputSource(is)); parsedResponse = "Response handled by custom SAX content handler"; } else { parsedResponse = parseXML(response); } } else if (dataType.equalsIgnoreCase("json")) { parsedResponse = parseJSON(response); } else if (dataType.equalsIgnoreCase("script")) { parsedResponse = parseScript(response); } else if (dataType.equalsIgnoreCase("image")) { parsedResponse = parseImage(response); } } catch (ClientProtocolException cpe) { if (options.debug()) cpe.printStackTrace(); success = false; Error e = new Error(); AjaxError error = new AjaxError(); error.request = request; error.options = options; e.status = statusLine.getStatusCode(); e.reason = statusLine.getReasonPhrase(); error.status = e.status; error.reason = e.reason; e.headers = response.getAllHeaders(); e.error = error; return e; } catch (Exception ioe) { if (options.debug()) ioe.printStackTrace(); success = false; Error e = new Error(); AjaxError error = new AjaxError(); error.request = request; error.options = options; e.status = statusLine.getStatusCode(); e.reason = statusLine.getReasonPhrase(); error.status = e.status; error.reason = e.reason; e.headers = response.getAllHeaders(); e.error = error; return e; } if (success) { //Handle cases where successful requests still return errors (these include //configurations in AjaxOptions and HTTP Headers String key = String.format(Locale.US, "%s_?=%s", options.url(), options.dataType()); CachedResponse cache = URLresponses.get(key); Date now = new Date(); //handle ajax caching option if (cache != null) { if (options.cache()) { if (now.getTime() - cache.timestamp.getTime() < options.cacheTimeout()) { parsedResponse = cache; } else { cache.response = parsedResponse; cache.timestamp = now; synchronized (URLresponses) { URLresponses.put(key, cache); } } } } //handle ajax ifModified option Header[] lastModifiedHeaders = response.getHeaders("last-modified"); if (lastModifiedHeaders.length >= 1) { try { Header h = lastModifiedHeaders[0]; SimpleDateFormat format = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz"); Date lastModified = format.parse(h.getValue()); if (options.ifModified() && lastModified != null) { if (cache.lastModified != null && cache.lastModified.compareTo(lastModified) == 0) { //request response has not been modified. //Causes an error instead of a success. Error e = new Error(); AjaxError error = new AjaxError(); error.request = request; error.options = options; e.status = statusLine.getStatusCode(); e.reason = statusLine.getReasonPhrase(); error.status = e.status; error.reason = e.reason; e.headers = response.getAllHeaders(); e.error = error; Function func = options.statusCode().get(304); if (func != null) { if (options.context() != null) func.invoke(new $(options.context())); else func.invoke(null); } return e; } else { cache.lastModified = lastModified; synchronized (URLresponses) { URLresponses.put(key, cache); } } } } catch (Throwable t) { Log.e("Ajax", "Could not parse Last-Modified Header"); } } //Now handle a successful request Success s = new Success(); s.obj = parsedResponse; s.reason = statusLine.getReasonPhrase(); s.headers = response.getAllHeaders(); return s; } //success Success s = new Success(); s.obj = parsedResponse; s.reason = statusLine.getReasonPhrase(); s.headers = response.getAllHeaders(); return s; } } catch (Throwable t) { if (options.debug()) t.printStackTrace(); if (t instanceof java.net.SocketTimeoutException) { Error e = new Error(); AjaxError error = new AjaxError(); error.request = request; error.options = options; e.status = 0; String reason = t.getMessage(); if (reason == null) reason = "Socket Timeout"; e.reason = reason; error.status = e.status; error.reason = e.reason; if (response != null) e.headers = response.getAllHeaders(); else e.headers = new Header[0]; e.error = error; return e; } return null; } }
From source file:sabina.integration.TestScenario.java
private HttpUriRequest getHttpRequest(String method, String path, String body, boolean secure, String acceptType) {// www . j av a 2 s .c o m if (body == null) body = ""; try { String protocol = secure ? "https" : "http"; String uri = protocol + "://localhost:" + port + path; if (method.equals("GET")) { HttpGet httpGet = new HttpGet(uri); httpGet.setHeader("Accept", acceptType); return httpGet; } if (method.equals("POST")) { HttpPost httpPost = new HttpPost(uri); httpPost.setHeader("Accept", acceptType); httpPost.setEntity(new StringEntity(body)); return httpPost; } if (method.equals("PATCH")) { HttpPatch httpPatch = new HttpPatch(uri); httpPatch.setHeader("Accept", acceptType); httpPatch.setEntity(new StringEntity(body)); return httpPatch; } if (method.equals("DELETE")) { HttpDelete httpDelete = new HttpDelete(uri); httpDelete.setHeader("Accept", acceptType); return httpDelete; } if (method.equals("PUT")) { HttpPut httpPut = new HttpPut(uri); httpPut.setHeader("Accept", acceptType); httpPut.setEntity(new StringEntity(body)); return httpPut; } if (method.equals("HEAD")) return new HttpHead(uri); if (method.equals("TRACE")) return new HttpTrace(uri); if (method.equals("OPTIONS")) return new HttpOptions(uri); throw new IllegalArgumentException("Unknown method " + method); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } }
From source file:com.github.seratch.signedrequest4j.SignedRequestApacheHCImpl.java
static HttpUriRequest getRequest(HttpMethod method, String url) { if (method == HttpMethod.GET) { return new HttpGet(url); } else if (method == HttpMethod.POST) { return new HttpPost(url); } else if (method == HttpMethod.PUT) { return new HttpPut(url); } else if (method == HttpMethod.DELETE) { return new HttpDelete(url); } else if (method == HttpMethod.HEAD) { return new HttpHead(url); } else if (method == HttpMethod.OPTIONS) { return new HttpOptions(url); } else if (method == HttpMethod.TRACE) { return new HttpTrace(url); } else {//w w w . j av a 2s. c om return null; } }
From source file:com.basho.riak.client.util.ClientHelper.java
/** * Same as {@link RiakClient}, except only returning the HTTP response *//*from w ww . ja v a2 s . c o m*/ public HttpResponse fetchMeta(String bucket, String key, RequestMeta meta) { if (meta == null) { meta = new RequestMeta(); } if (meta.getQueryParam(Constants.QP_R) == null) { meta.setQueryParam(Constants.QP_R, Constants.DEFAULT_R.toString()); } HttpHead head = new HttpHead(ClientUtils.makeURI(config, bucket, key)); return executeMethod(bucket, key, head, meta); }
From source file:com.mobiperf_library.measurements.HttpTask.java
/** Runs the HTTP measurement task. Will acquire power lock to ensure wifi * is not turned off *//*from www . j a v a 2 s . co m*/ @Override 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; TaskProgress taskProgress = TaskProgress.FAILED; String errorMsg = ""; InputStream inputStream = null; 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()); 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(); if (statusCode == 200) { taskProgress = TaskProgress.COMPLETED; } else { taskProgress = TaskProgress.FAILED; } } /* 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); } } duration = System.currentTimeMillis() - startTime;//TODO check this } 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, taskProgress, this.measurementDesc); result.addResult("code", statusCode); if (taskProgress == TaskProgress.COMPLETED) { 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)); MeasurementResult[] mrArray = new MeasurementResult[1]; mrArray[0] = result; return mrArray; } 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:io.crate.integrationtests.BlobHttpIntegrationTest.java
protected CloseableHttpResponse head(String uri) throws IOException { HttpHead httpHead = new HttpHead(String.format(Locale.ENGLISH, "http://%s:%s/_blobs/%s", address.getHostName(), address.getPort(), uri)); return executeAndDefaultAssertions(httpHead); }
From source file:com.mobilyzer.measurements.HttpTask.java
/** Runs the HTTP measurement task. Will acquire power lock to ensure wifi * is not turned off *//* w ww. ja v a 2 s . c om*/ @Override 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; TaskProgress taskProgress = TaskProgress.FAILED; String errorMsg = ""; InputStream inputStream = null; long currentRxTx = Util.getCurrentRxTxBytes(); 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()); 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(); if (statusCode == 200) { taskProgress = TaskProgress.COMPLETED; } else { taskProgress = TaskProgress.FAILED; } } /* 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); } } duration = System.currentTimeMillis() - startTime;//TODO check this } 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(this.getKey()), HttpTask.TYPE, System.currentTimeMillis() * 1000, taskProgress, this.measurementDesc); result.addResult("code", statusCode); dataConsumed += (Util.getCurrentRxTxBytes() - currentRxTx); if (taskProgress == TaskProgress.COMPLETED) { 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)); MeasurementResult[] mrArray = new MeasurementResult[1]; mrArray[0] = result; return mrArray; } 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:com.mobilyzer.measurements.HttpTask_original.java
/** Runs the HTTP measurement task. Will acquire power lock to ensure wifi * is not turned off *///from w w w . ja va 2s. co m @Override 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_original.MAX_BODY_SIZE_TO_UPLOAD); // boolean success = false; TaskProgress taskProgress = TaskProgress.FAILED; String errorMsg = ""; InputStream inputStream = null; long currentRxTx = Util.getCurrentRxTxBytes(); 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()); 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(); if (statusCode == 200) { taskProgress = TaskProgress.COMPLETED; } else { taskProgress = TaskProgress.FAILED; } } /* 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); } } duration = System.currentTimeMillis() - startTime;//TODO check this } 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(this.getKey()), HttpTask.TYPE, System.currentTimeMillis() * 1000, taskProgress, this.measurementDesc); result.addResult("code", statusCode); dataConsumed += (Util.getCurrentRxTxBytes() - currentRxTx); if (taskProgress == TaskProgress.COMPLETED) { 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)); MeasurementResult[] mrArray = new MeasurementResult[1]; mrArray[0] = result; return mrArray; } 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); }