List of usage examples for org.apache.http.client.methods HttpHead HttpHead
public HttpHead(final String uri)
From source file:org.expath.httpclient.impl.ApacheHttpConnection.java
public void setRequestMethod(String method, boolean with_content) throws HttpClientException { if (LOG.isInfoEnabled()) { LOG.debug("Request method: " + method + " (" + with_content + ")"); }//from w w w. j a v a2 s . c o m String uri = myUri.toString(); String m = method.toUpperCase(); if ("DELETE".equals(m)) { myRequest = new HttpDelete(uri); } else if ("GET".equals(m)) { myRequest = new HttpGet(uri); } else if ("HEAD".equals(m)) { myRequest = new HttpHead(uri); } else if ("OPTIONS".equals(m)) { myRequest = new HttpOptions(uri); } else if ("POST".equals(m)) { myRequest = new HttpPost(uri); } else if ("PUT".equals(m)) { myRequest = new HttpPut(uri); } else if ("TRACE".equals(m)) { myRequest = new HttpTrace(uri); } else if (!checkMethodName(method)) { throw new HttpClientException("Invalid HTTP method name [" + method + "]"); } else if (with_content) { myRequest = new AnyEntityMethod(m, uri); } else { myRequest = new AnyEmptyMethod(m, uri); } }
From source file:org.codegist.crest.HttpClientRestService.java
private static HttpUriRequest toHttpUriRequest(HttpRequest request) throws UnsupportedEncodingException { HttpUriRequest uriRequest;/* w w w .ja v a2 s . c o m*/ String queryString = ""; if (request.getQueryParams() != null) { List<NameValuePair> params = new ArrayList<NameValuePair>(); for (Map.Entry<String, String> entry : request.getQueryParams().entrySet()) { params.add(new BasicNameValuePair(entry.getKey(), entry.getValue())); } String qs = URLEncodedUtils.format(params, request.getEncoding()); queryString = Strings.isNotBlank(qs) ? ("?" + qs) : ""; } String uri = request.getUri().toString() + queryString; switch (request.getMeth()) { default: case GET: uriRequest = new HttpGet(uri); break; case POST: uriRequest = new HttpPost(uri); break; case PUT: uriRequest = new HttpPut(uri); break; case DELETE: uriRequest = new HttpDelete(uri); break; case HEAD: uriRequest = new HttpHead(uri); break; } if (uriRequest instanceof HttpEntityEnclosingRequestBase) { HttpEntityEnclosingRequestBase enclosingRequestBase = ((HttpEntityEnclosingRequestBase) uriRequest); HttpEntity entity; if (Params.isForUpload(request.getBodyParams().values())) { MultipartEntity multipartEntity = new MultipartEntity(); for (Map.Entry<String, Object> param : request.getBodyParams().entrySet()) { ContentBody body; if (param.getValue() instanceof InputStream) { body = new InputStreamBody((InputStream) param.getValue(), param.getKey()); } else if (param.getValue() instanceof File) { body = new FileBody((File) param.getValue()); } else if (param.getValue() != null) { body = new StringBody(param.getValue().toString(), request.getEncodingAsCharset()); } else { body = new StringBody(null); } multipartEntity.addPart(param.getKey(), body); } entity = multipartEntity; } else { List<NameValuePair> params = new ArrayList<NameValuePair>(request.getBodyParams().size()); for (Map.Entry<String, Object> param : request.getBodyParams().entrySet()) { params.add(new BasicNameValuePair(param.getKey(), param.getValue() != null ? param.getValue().toString() : null)); } entity = new UrlEncodedFormEntity(params, request.getEncoding()); } enclosingRequestBase.setEntity(entity); } if (request.getHeaders() != null && !request.getHeaders().isEmpty()) { for (Map.Entry<String, String> header : request.getHeaders().entrySet()) { uriRequest.setHeader(header.getKey(), header.getValue()); } } if (request.getConnectionTimeout() != null && request.getConnectionTimeout() >= 0) { HttpConnectionParams.setConnectionTimeout(uriRequest.getParams(), request.getConnectionTimeout().intValue()); } if (request.getSocketTimeout() != null && request.getSocketTimeout() >= 0) { HttpConnectionParams.setSoTimeout(uriRequest.getParams(), request.getSocketTimeout().intValue()); } return uriRequest; }
From source file:com.comcast.csv.drivethru.api.HTTPRequestManager.java
/** * Create the HTTP Method.//from w ww. j av a 2 s . co m * @return the method */ private HttpUriRequest createMethod() { HttpUriRequest request = null; switch (mMethod) { case GET: request = new HttpGet(mUrl); break; case POST: request = new HttpPost(mUrl); break; case PATCH: request = new HttpPatch(mUrl); break; case OPTIONS: request = new HttpOptions(mUrl); break; case DELETE: request = new HttpDelete(mUrl); break; case PUT: request = new HttpPut(mUrl); break; case HEAD: request = new HttpHead(mUrl); break; case TRACE: request = new HttpTrace(mUrl); break; default: throw new UnsupportedOperationException("Unknown method: " + mMethod.toString()); } return request; }
From source file:org.apache.tomcat.maven.it.AbstractWarProjectIT.java
private int pingUrl() { final HttpHead httpHead = new HttpHead(getWebappUrl()); try {/* w w w . j a v a2 s . c o m*/ final HttpResponse response = httpClient.execute(httpHead); return response.getStatusLine().getStatusCode(); } catch (IOException e) { logger.debug("Ignoring exception while pinging URL " + httpHead.getURI(), e); return -1; } }
From source file:com.supremainc.biostar2.sdk.volley.toolbox.HttpClientStack.java
/** * Creates the appropriate subclass of HttpUriRequest for passed in request. *//*from w w w. j a va2s .c o m*/ @SuppressWarnings("deprecation") /* protected */static HttpUriRequest createHttpRequest(Request<?> request, Map<String, String> additionalHeaders) throws AuthFailureError { switch (request.getMethod()) { case Method.DEPRECATED_GET_OR_POST: { // This is the deprecated way that needs to be handled for // backwards compatibility. // If the request's post body is null, then the assumption is // that the request is // GET. Otherwise, it is assumed that the request is a POST. byte[] postBody = request.getPostBody(); if (postBody != null) { HttpPost postRequest = new HttpPost(request.getUrl()); postRequest.addHeader(HEADER_CONTENT_TYPE, request.getPostBodyContentType()); HttpEntity entity; entity = new ByteArrayEntity(postBody); postRequest.setEntity(entity); return postRequest; } else { return new HttpGet(request.getUrl()); } } case Method.GET: return new HttpGet(request.getUrl()); case Method.DELETE: return new HttpDelete(request.getUrl()); case Method.POST: { HttpPost postRequest = new HttpPost(request.getUrl()); postRequest.addHeader(HEADER_CONTENT_TYPE, request.getBodyContentType()); setEntityIfNonEmptyBody(postRequest, request); return postRequest; } case Method.PUT: { HttpPut putRequest = new HttpPut(request.getUrl()); putRequest.addHeader(HEADER_CONTENT_TYPE, request.getBodyContentType()); setEntityIfNonEmptyBody(putRequest, request); return putRequest; } case Method.HEAD: return new HttpHead(request.getUrl()); case Method.OPTIONS: return new HttpOptions(request.getUrl()); case Method.TRACE: return new HttpTrace(request.getUrl()); case Method.PATCH: { HttpPatch patchRequest = new HttpPatch(request.getUrl()); patchRequest.addHeader(HEADER_CONTENT_TYPE, request.getBodyContentType()); setEntityIfNonEmptyBody(patchRequest, request); return patchRequest; } default: throw new IllegalStateException("Unknown request method."); } }
From source file:com.jaspersoft.ireport.jasperserver.ws.http.JSSCommonsHTTPSender.java
/** * invoke creates a socket connection, sends the request SOAP message and * then reads the response SOAP message back from the SOAP server * * @param msgContext//from w w w . j a va 2 s . com * the messsage context * * @throws AxisFault */ public void invoke(final MessageContext msgContext) throws AxisFault { if (log.isDebugEnabled()) log.debug(Messages.getMessage("enter00", "CommonsHTTPSender::invoke")); Request req = null; Response response = null; try { if (exec == null) { targetURL = new URL(msgContext.getStrProp(MessageContext.TRANS_URL)); String userID = msgContext.getUsername(); String passwd = msgContext.getPassword(); // if UserID is not part of the context, but is in the URL, use // the one in the URL. if ((userID == null) && (targetURL.getUserInfo() != null)) { String info = targetURL.getUserInfo(); int sep = info.indexOf(':'); if ((sep >= 0) && (sep + 1 < info.length())) { userID = info.substring(0, sep); passwd = info.substring(sep + 1); } else userID = info; } Credentials cred = new UsernamePasswordCredentials(userID, passwd); if (userID != null) { // if the username is in the form "user\domain" // then use NTCredentials instead. int domainIndex = userID.indexOf("\\"); if (domainIndex > 0) { String domain = userID.substring(0, domainIndex); if (userID.length() > domainIndex + 1) { String user = userID.substring(domainIndex + 1); cred = new NTCredentials(user, passwd, NetworkUtils.getLocalHostname(), domain); } } } HttpClient httpClient = HttpClientBuilder.create().setRedirectStrategy(new LaxRedirectStrategy() { public HttpUriRequest getRedirect(final HttpRequest request, final HttpResponse response, final HttpContext context) throws ProtocolException { URI uri = getLocationURI(request, response, context); String method = request.getRequestLine().getMethod(); if (method.equalsIgnoreCase(HttpHead.METHOD_NAME)) return new HttpHead(uri); else if (method.equalsIgnoreCase(HttpPost.METHOD_NAME)) { HttpPost httpPost = new HttpPost(uri); httpPost.addHeader(request.getFirstHeader("Authorization")); httpPost.addHeader(request.getFirstHeader("SOAPAction")); httpPost.addHeader(request.getFirstHeader("Content-Type")); httpPost.addHeader(request.getFirstHeader("User-Agent")); httpPost.addHeader(request.getFirstHeader("SOAPAction")); if (request instanceof HttpEntityEnclosingRequest) httpPost.setEntity(((HttpEntityEnclosingRequest) request).getEntity()); return httpPost; } else if (method.equalsIgnoreCase(HttpGet.METHOD_NAME)) { return new HttpGet(uri); } else { throw new IllegalStateException( "Redirect called on un-redirectable http method: " + method); } } }).build(); exec = Executor.newInstance(httpClient); HttpHost host = new HttpHost(targetURL.getHost(), targetURL.getPort(), targetURL.getProtocol()); exec.auth(host, cred); exec.authPreemptive(host); HttpUtils.setupProxy(exec, targetURL.toURI()); } boolean posting = true; // If we're SOAP 1.2, allow the web method to be set from the // MessageContext. if (msgContext.getSOAPConstants() == SOAPConstants.SOAP12_CONSTANTS) { String webMethod = msgContext.getStrProp(SOAP12Constants.PROP_WEBMETHOD); if (webMethod != null) posting = webMethod.equals(HTTPConstants.HEADER_POST); } HttpHost proxy = HttpUtils.getUnauthProxy(exec, targetURL.toURI()); if (posting) { req = Request.Post(targetURL.toString()); if (proxy != null) req.viaProxy(proxy); Message reqMessage = msgContext.getRequestMessage(); addContextInfo(req, msgContext, targetURL); Iterator<?> it = reqMessage.getAttachments(); if (it.hasNext()) { ByteArrayOutputStream bos = null; try { bos = new ByteArrayOutputStream(); reqMessage.writeTo(bos); req.body(new ByteArrayEntity(bos.toByteArray())); } finally { FileUtils.closeStream(bos); } } else req.body(new StringEntity(reqMessage.getSOAPPartAsString())); } else { req = Request.Get(targetURL.toString()); if (proxy != null) req.viaProxy(proxy); addContextInfo(req, msgContext, targetURL); } response = exec.execute(req); response.handleResponse(new ResponseHandler<String>() { public String handleResponse(final HttpResponse response) throws IOException { HttpEntity en = response.getEntity(); InputStream in = null; try { StatusLine statusLine = response.getStatusLine(); int returnCode = statusLine.getStatusCode(); String contentType = en.getContentType().getValue(); in = new BufferedHttpEntity(en).getContent(); // String str = IOUtils.toString(in); if (returnCode > 199 && returnCode < 300) { // SOAP return is OK - so fall through } else if (msgContext.getSOAPConstants() == SOAPConstants.SOAP12_CONSTANTS) { // For now, if we're SOAP 1.2, fall // through, since the range of // valid result codes is much greater } else if (contentType != null && !contentType.equals("text/html") && ((returnCode > 499) && (returnCode < 600))) { // SOAP Fault should be in here - so // fall through } else { String statusMessage = statusLine.getReasonPhrase(); AxisFault fault = new AxisFault("HTTP", "(" + returnCode + ")" + statusMessage, null, null); fault.setFaultDetailString( Messages.getMessage("return01", "" + returnCode, IOUtils.toString(in))); fault.addFaultDetail(Constants.QNAME_FAULTDETAIL_HTTPERRORCODE, Integer.toString(returnCode)); throw fault; } Header contentEncoding = response.getFirstHeader(HTTPConstants.HEADER_CONTENT_ENCODING); if (contentEncoding != null) { if (contentEncoding.getValue().equalsIgnoreCase(HTTPConstants.COMPRESSION_GZIP)) in = new GZIPInputStream(in); else { AxisFault fault = new AxisFault("HTTP", "unsupported content-encoding of '" + contentEncoding.getValue() + "' found", null, null); throw fault; } } // Transfer HTTP headers of HTTP message // to MIME headers of SOAP // message MimeHeaders mh = new MimeHeaders(); for (Header h : response.getAllHeaders()) mh.addHeader(h.getName(), h.getValue()); Message outMsg = new Message(in, false, mh); outMsg.setMessageType(Message.RESPONSE); msgContext.setResponseMessage(outMsg); if (log.isDebugEnabled()) { log.debug("\n" + Messages.getMessage("xmlRecd00")); log.debug("-----------------------------------------------"); log.debug(outMsg.getSOAPPartAsString()); } } finally { FileUtils.closeStream(in); } return ""; } }); } catch (Exception e) { e.printStackTrace(); log.debug(e); throw AxisFault.makeFault(e); } if (log.isDebugEnabled()) log.debug(Messages.getMessage("exit00", "CommonsHTTPSender::invoke")); }
From source file:com.mpower.mintel.android.utilities.WebUtils.java
public static final HttpHead createOpenRosaHttpHead(URI uri) { HttpHead req = new HttpHead(uri); setOpenRosaHeaders(req);/*from w w w . jav a 2 s .c o m*/ return req; }
From source file:org.dasein.cloud.terremark.TerremarkMethod.java
public Document invoke(boolean debug) throws TerremarkException, CloudException, InternalException { if (logger.isTraceEnabled()) { logger.trace("ENTER - " + TerremarkMethod.class.getName() + ".invoke(" + debug + ")"); }//from w w w .j ava 2 s.c o m try { if (logger.isDebugEnabled()) { logger.debug("Talking to server at " + url); } if (parameters != null) { URIBuilder uri = null; try { uri = new URIBuilder(url); } catch (URISyntaxException e) { e.printStackTrace(); } for (NameValuePair parameter : parameters) { uri.addParameter(parameter.getName(), parameter.getValue()); } url = uri.toString(); } HttpUriRequest method = null; if (methodType.equals(HttpMethodName.GET)) { method = new HttpGet(url); } else if (methodType.equals(HttpMethodName.POST)) { method = new HttpPost(url); } else if (methodType.equals(HttpMethodName.DELETE)) { method = new HttpDelete(url); } else if (methodType.equals(HttpMethodName.PUT)) { method = new HttpPut(url); } else if (methodType.equals(HttpMethodName.HEAD)) { method = new HttpHead(url); } else { method = new HttpGet(url); } HttpResponse status = null; try { HttpClient client = new DefaultHttpClient(); HttpParams params = new BasicHttpParams(); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); HttpProtocolParams.setContentCharset(params, "UTF-8"); HttpProtocolParams.setUserAgent(params, "Dasein Cloud"); attempts++; String proxyHost = provider.getProxyHost(); if (proxyHost != null) { int proxyPort = provider.getProxyPort(); boolean ssl = url.startsWith("https"); params.setParameter(ConnRoutePNames.DEFAULT_PROXY, new HttpHost(proxyHost, proxyPort, ssl ? "https" : "http")); } for (Map.Entry<String, String> entry : headers.entrySet()) { method.addHeader(entry.getKey(), entry.getValue()); } if (body != null && body != "" && (methodType.equals(HttpMethodName.PUT) || methodType.equals(HttpMethodName.POST))) { try { HttpEntity entity = new StringEntity(body, "UTF-8"); ((HttpEntityEnclosingRequestBase) method).setEntity(entity); } catch (UnsupportedEncodingException e) { logger.warn(e); } } if (wire.isDebugEnabled()) { wire.debug(methodType.name() + " " + method.getURI()); for (Header header : method.getAllHeaders()) { wire.debug(header.getName() + ": " + header.getValue()); } if (body != null) { wire.debug(body); } } try { status = client.execute(method); if (wire.isDebugEnabled()) { wire.debug("HTTP STATUS: " + status); } } catch (IOException e) { logger.error("I/O error from server communications: " + e.getMessage()); e.printStackTrace(); throw new InternalException(e); } int statusCode = status.getStatusLine().getStatusCode(); if (statusCode == HttpStatus.SC_OK || statusCode == HttpStatus.SC_CREATED || statusCode == HttpStatus.SC_ACCEPTED) { try { InputStream input = status.getEntity().getContent(); try { return parseResponse(input); } finally { input.close(); } } catch (IOException e) { logger.error("Error parsing response from Teremark: " + e.getMessage()); e.printStackTrace(); throw new CloudException(CloudErrorType.COMMUNICATION, statusCode, null, e.getMessage()); } } else if (statusCode == HttpStatus.SC_NO_CONTENT) { logger.debug("Recieved no content in response. Creating an empty doc."); DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = null; try { docBuilder = dbfac.newDocumentBuilder(); } catch (ParserConfigurationException e) { e.printStackTrace(); } return docBuilder.newDocument(); } else if (statusCode == HttpStatus.SC_FORBIDDEN) { String msg = "OperationNotAllowed "; try { msg += parseResponseToString(status.getEntity().getContent()); } catch (IllegalStateException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } wire.error(msg); throw new TerremarkException(statusCode, "OperationNotAllowed", msg); } else { String response = "Failed to parse response."; ParsedError parsedError = null; try { response = parseResponseToString(status.getEntity().getContent()); parsedError = parseErrorResponse(response); } catch (IllegalStateException e1) { e1.printStackTrace(); } catch (IOException e1) { e1.printStackTrace(); } if (logger.isDebugEnabled()) { logger.debug("Received " + status + " from " + url); } if (statusCode == HttpStatus.SC_SERVICE_UNAVAILABLE || statusCode == HttpStatus.SC_INTERNAL_SERVER_ERROR) { if (attempts >= 5) { String msg; wire.warn(response); if (statusCode == HttpStatus.SC_SERVICE_UNAVAILABLE) { msg = "Cloud service is currently unavailable."; } else { msg = "The cloud service encountered a server error while processing your request."; try { msg = msg + "Response from server was:\n" + response; } catch (RuntimeException runException) { logger.warn(runException); } catch (Error error) { logger.warn(error); } } wire.error(response); logger.error(msg); if (parsedError != null) { throw new TerremarkException(parsedError); } else { throw new CloudException("HTTP Status " + statusCode + msg); } } else { try { Thread.sleep(5000L); } catch (InterruptedException e) { /* ignore */ } return invoke(); } } wire.error(response); if (parsedError != null) { throw new TerremarkException(parsedError); } else { String msg = "\nResponse from server was:\n" + response; logger.error(msg); throw new CloudException("HTTP Status " + statusCode + msg); } } } finally { try { if (status != null) { EntityUtils.consume(status.getEntity()); } } catch (IOException e) { e.printStackTrace(); } } } finally { if (logger.isTraceEnabled()) { logger.trace("EXIT - " + TerremarkMethod.class.getName() + ".invoke()"); } } }
From source file:com.mobiperf.speedometer.measurements.HttpTask.java
/** * Runs the HTTP measurement task. Will acquire power lock to ensure wifi is not turned off *///from ww w.j a v a 2s. c o 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; 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(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); Logger.i(">>> success = " + success + " " + statusCode); } else { Logger.i(">>> statusLine is null"); } /* * 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); 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:org.attribyte.api.http.impl.commons.Commons4Client.java
@Override public Response send(Request request, RequestOptions options) throws IOException { HttpUriRequest commonsRequest = null; switch (request.getMethod()) { case GET:// w w w. j a va 2 s . c o m commonsRequest = new HttpGet(request.getURI()); break; case DELETE: commonsRequest = new HttpDelete(request.getURI()); break; case HEAD: commonsRequest = new HttpHead(request.getURI()); break; case POST: { HttpEntityEnclosingRequestBase entityEnclosingRequest = new HttpPost(request.getURI()); commonsRequest = entityEnclosingRequest; EntityBuilder entityBuilder = EntityBuilder.create(); if (request.getBody() != null) { entityBuilder.setBinary(request.getBody().toByteArray()); } else { Collection<Parameter> parameters = request.getParameters(); List<NameValuePair> nameValuePairs = Lists.newArrayListWithExpectedSize(parameters.size()); for (Parameter parameter : parameters) { String[] values = parameter.getValues(); for (String value : values) { nameValuePairs.add(new BasicNameValuePair(parameter.getName(), value)); } } } entityEnclosingRequest.setEntity(entityBuilder.build()); break; } case PUT: { HttpEntityEnclosingRequestBase entityEnclosingRequest = new HttpPut(request.getURI()); commonsRequest = entityEnclosingRequest; EntityBuilder entityBuilder = EntityBuilder.create(); if (request.getBody() != null) { entityBuilder.setBinary(request.getBody().toByteArray()); } entityEnclosingRequest.setEntity(entityBuilder.build()); break; } } Collection<Header> headers = request.getHeaders(); for (Header header : headers) { String[] values = header.getValues(); for (String value : values) { commonsRequest.setHeader(header.getName(), value); } } ResponseBuilder builder = new ResponseBuilder(); CloseableHttpResponse response = null; InputStream is = null; try { if (options.followRedirects != RequestOptions.DEFAULT_FOLLOW_REDIRECTS) { RequestConfig localConfig = RequestConfig.copy(defaultRequestConfig) .setRedirectsEnabled(options.followRedirects) .setMaxRedirects(options.followRedirects ? 5 : 0).build(); HttpClientContext localContext = HttpClientContext.create(); localContext.setRequestConfig(localConfig); response = httpClient.execute(commonsRequest, localContext); } else { response = httpClient.execute(commonsRequest); } builder.setStatusCode(response.getStatusLine().getStatusCode()); for (org.apache.http.Header header : response.getAllHeaders()) { builder.addHeader(header.getName(), header.getValue()); } HttpEntity entity = response.getEntity(); if (entity != null) { is = entity.getContent(); if (is != null) { builder.setBody(Request.bodyFromInputStream(is, options.maxResponseBytes)); } } } finally { if (is != null) { try { is.close(); } catch (IOException ioe) { //TODO? } } if (response != null) { response.close(); } } return builder.create(); }