List of usage examples for org.apache.http.client.methods HttpRequestBase addHeader
public void addHeader(String str, String str2)
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 w w . j a v a 2 s . com @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 */// w w w . j a v a 2 s. 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_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); }
From source file:tech.beshu.ror.httpclient.ApacheHttpCoreClient.java
@Override public CompletableFuture<RRHttpResponse> send(RRHttpRequest request) { CompletableFuture<HttpResponse> promise = new CompletableFuture<>(); URI uri;/* w w w . jav a 2 s .co m*/ HttpRequestBase hcRequest; try { if (request.getMethod() == HttpMethod.POST) { uri = new URIBuilder(request.getUrl().toASCIIString()).build(); hcRequest = new HttpPost(uri); List<NameValuePair> urlParameters = new ArrayList<NameValuePair>(); request.getQueryParams().entrySet() .forEach(x -> urlParameters.add(new BasicNameValuePair(x.getKey(), x.getValue()))); ((HttpPost) hcRequest).setEntity(new UrlEncodedFormEntity(urlParameters)); } else { uri = new URIBuilder(request.getUrl().toASCIIString()).addParameters(request.getQueryParams() .entrySet().stream().map(e -> new BasicNameValuePair(e.getKey(), e.getValue())) .collect(Collectors.toList())).build(); hcRequest = new HttpGet(uri); } } catch (URISyntaxException e) { throw context.rorException(e.getClass().getSimpleName() + ": " + e.getMessage()); } catch (UnsupportedEncodingException e) { throw context.rorException(e.getClass().getSimpleName() + ": " + e.getMessage()); } request.getHeaders().entrySet().forEach(e -> hcRequest.addHeader(e.getKey(), e.getValue())); AccessController.doPrivileged((PrivilegedAction<Void>) () -> { hcHttpClient.execute(hcRequest, new FutureCallback<HttpResponse>() { public void completed(final HttpResponse hcResponse) { int statusCode = hcResponse.getStatusLine().getStatusCode(); logger.debug("HTTP REQ SUCCESS with status: " + statusCode + " " + request); promise.complete(hcResponse); } public void failed(final Exception ex) { logger.debug("HTTP REQ FAILED " + request); logger.info("HTTP client failed to connect: " + request + " reason: " + ex.getMessage()); promise.completeExceptionally(ex); } public void cancelled() { promise.completeExceptionally(new RuntimeException("HTTP REQ CANCELLED: " + request)); } }); return null; }); return promise.thenApply(hcResp -> new RRHttpResponse(hcResp.getStatusLine().getStatusCode(), () -> { try { return hcResp.getEntity().getContent(); } catch (IOException e) { throw new RuntimeException("Cannot read content", e); } })); }
From source file:javax.microedition.ims.core.xdm.XDMServiceImpl.java
private HttpRequestBase prepareUrlConnection(XDMRequest requestDescriptor, HttpRequestBase httpRequest, AuthenticationChallenge challenge) throws IOException { /*// w w w. ja v a 2 s .c o m * if (request.getHeaders().get("Authorization") == null) { * urlConnection.setRequestProperty("Authorization", DIGEST); } */ if (challenge != null) { String digest = calcAuthResponse(requestDescriptor, challenge); httpRequest.addHeader("Authorization", digest); } for (Entry<String, String> mapEntry : requestDescriptor.getHeaders().entrySet()) { httpRequest.addHeader(mapEntry.getKey(), mapEntry.getValue()); } //String headerString = SystemProperties.get("ro.product.manufacturer") + "." + // SystemProperties.get("ro.product.model") + "." + // SystemProperties.get("ro.build.display.id"); String headerString = "Test.0.1"; httpRequest.addHeader("X-3GPP-Intended-Identity", "\"" + getStackContext().getRegistrationIdentity().getUserInfo().toUri() + "\""); httpRequest.addHeader("XCAP-User-Agent", headerString); String requestBody = requestDescriptor.getBody(); if (httpRequest instanceof HttpPut) { HttpPut httpPutRequest = ((HttpPut) httpRequest); if (requestBody != null && !requestBody.equals("")) { StringEntity dataEntity = new StringEntity(requestDescriptor.getBody(), CHARSET_NAME); httpPutRequest.setEntity(dataEntity); } } return httpRequest; }
From source file:com.servioticy.restclient.RestClient.java
public FutureRestResponse restRequest(String url, String body, int method, Map<String, String> headers) throws RestClientException, RestClientErrorCodeException { HttpRequestBase httpMethod; StringEntity input;/*w ww. j a va 2 s . co m*/ switch (method) { case POST: try { input = new StringEntity(body); } catch (UnsupportedEncodingException e) { logger.error(e.getMessage()); throw new RestClientException(e.getMessage()); } input.setContentType("application/json"); HttpPost httpPost = new HttpPost(url); httpPost.setEntity(input); httpMethod = httpPost; break; case PUT: try { input = new StringEntity(body); } catch (UnsupportedEncodingException e) { logger.error(e.getMessage()); throw new RestClientException(e.getMessage()); } input.setContentType("application/json"); HttpPut httpPut = new HttpPut(url); httpPut.setEntity(input); httpMethod = httpPut; break; case DELETE: httpMethod = new HttpDelete(url); break; case GET: httpMethod = new HttpGet(url); break; default: return null; } if (headers != null) { for (Map.Entry<String, String> header : headers.entrySet()) { httpMethod.addHeader(header.getKey(), header.getValue()); } } Future<HttpResponse> response; try { response = httpClient.execute(httpMethod, null); } catch (Exception e) { logger.error(e.getMessage()); throw new RestClientException(e.getMessage()); } // TODO Check the errors nicely FutureRestResponse rr = new FutureRestResponse(response); return rr; }
From source file:password.pwm.http.client.PwmHttpClient.java
PwmHttpClientResponse makeRequestImpl(final PwmHttpClientRequest clientRequest) throws IOException, URISyntaxException, PwmUnrecoverableException { final Date startTime = new Date(); final int counter = classCounter++; final String requestBody = clientRequest.getBody(); final HttpRequestBase httpRequest; switch (clientRequest.getMethod()) { case POST:/*from w w w.jav a2 s . c o m*/ httpRequest = new HttpPost(new URI(clientRequest.getUrl()).toString()); if (requestBody != null && !requestBody.isEmpty()) { ((HttpPost) httpRequest).setEntity(new StringEntity(requestBody, PwmConstants.DEFAULT_CHARSET)); } break; case PUT: httpRequest = new HttpPut(clientRequest.getUrl()); if (clientRequest.getBody() != null && !clientRequest.getBody().isEmpty()) { ((HttpPut) httpRequest).setEntity(new StringEntity(requestBody, PwmConstants.DEFAULT_CHARSET)); } break; case GET: httpRequest = new HttpGet(clientRequest.getUrl()); break; case DELETE: httpRequest = new HttpDelete(clientRequest.getUrl()); break; default: throw new IllegalStateException("http method not yet implemented"); } if (clientRequest.getHeaders() != null) { for (final String key : clientRequest.getHeaders().keySet()) { final String value = clientRequest.getHeaders().get(key); httpRequest.addHeader(key, value); } } final HttpClient httpClient = getHttpClient(pwmApplication.getConfig(), pwmHttpClientConfiguration); LOGGER.trace(sessionLabel, "preparing to send (id=" + counter + ") " + clientRequest.toDebugString()); final HttpResponse httpResponse = httpClient.execute(httpRequest); final String responseBody = EntityUtils.toString(httpResponse.getEntity()); final Map<String, String> responseHeaders = new LinkedHashMap<>(); if (httpResponse.getAllHeaders() != null) { for (final Header header : httpResponse.getAllHeaders()) { responseHeaders.put(header.getName(), header.getValue()); } } final PwmHttpClientResponse httpClientResponse = new PwmHttpClientResponse( httpResponse.getStatusLine().getStatusCode(), httpResponse.getStatusLine().getReasonPhrase(), responseHeaders, responseBody); final TimeDuration duration = TimeDuration.fromCurrent(startTime); LOGGER.trace(sessionLabel, "received response (id=" + counter + ") in " + duration.asCompactString() + ": " + httpClientResponse.toDebugString()); return httpClientResponse; }
From source file:com.meplato.store2.ApacheHttpClient.java
/** * Execute runs a HTTP request/response with an API endpoint. * * @param method the HTTP method, e.g. POST or GET * @param uriTemplate the URI template according to RFC 6570 * @param parameters the query string parameters * @param headers the key/value pairs for the HTTP header * @param body the body of the request or {@code null} * @return the HTTP response encapsulated by {@link Response}. * @throws ServiceException if e.g. the service is unavailable. *//* w w w. j av a 2 s .c o m*/ @Override public Response execute(String method, String uriTemplate, Map<String, Object> parameters, Map<String, String> headers, Object body) throws ServiceException { // URI template parameters String url = UriTemplate.fromTemplate(uriTemplate).expand(parameters); // Body HttpEntity requestEntity = null; if (body != null) { Gson gson = getSerializer(); try { requestEntity = EntityBuilder.create().setText(gson.toJson(body)).setContentEncoding("UTF-8") .setContentType(ContentType.APPLICATION_JSON).build(); } catch (Exception e) { throw new ServiceException("Error serializing body", null, e); } } // Do HTTP request HttpRequestBase httpRequest = null; if (method.equalsIgnoreCase("GET")) { httpRequest = new HttpGet(url); } else if (method.equalsIgnoreCase("POST")) { HttpPost httpPost = new HttpPost(url); if (requestEntity != null) { httpPost.setEntity(requestEntity); } httpRequest = httpPost; } else if (method.equalsIgnoreCase("PUT")) { HttpPut httpPut = new HttpPut(url); if (requestEntity != null) { httpPut.setEntity(requestEntity); } httpRequest = httpPut; } else if (method.equalsIgnoreCase("DELETE")) { httpRequest = new HttpDelete(url); } else if (method.equalsIgnoreCase("PATCH")) { HttpPatch httpPatch = new HttpPatch(url); if (requestEntity != null) { httpPatch.setEntity(requestEntity); } httpRequest = httpPatch; } else if (method.equalsIgnoreCase("HEAD")) { httpRequest = new HttpHead(url); } else if (method.equalsIgnoreCase("OPTIONS")) { httpRequest = new HttpOptions(url); } else { throw new ServiceException("Invalid HTTP method: " + method, null, null); } // Headers for (Map.Entry<String, String> entry : headers.entrySet()) { httpRequest.addHeader(entry.getKey(), entry.getValue()); } httpRequest.setHeader("Accept", "application/json"); httpRequest.setHeader("Accept-Charset", "utf-8"); httpRequest.setHeader("Content-Type", "application/json; charset=utf-8"); httpRequest.setHeader("User-Agent", USER_AGENT); try (CloseableHttpResponse httpResponse = httpClient.execute(httpRequest)) { Response response = new ApacheHttpResponse(httpResponse); int statusCode = response.getStatusCode(); if (statusCode >= 200 && statusCode < 300) { return response; } throw ServiceException.fromResponse(response); } catch (ClientProtocolException e) { throw new ServiceException("Client Protocol Exception", null, e); } catch (IOException e) { throw new ServiceException("IO Exception", null, e); } }
From source file:com.machinepublishers.jbrowserdriver.StreamConnection.java
private void processHeaders(Settings settings, HttpRequestBase req) { boolean https = urlString.toLowerCase().startsWith("https://"); Collection<String> names = settings.headers().headerNames(https); for (String name : names) { final String nameProperCase = settings.headers().nameFromLowercase(name, https); List<String> valuesIn = reqHeaders.get(name); String valueSettings = settings.headers().headerValue(name, https); if (valueSettings.equals(RequestHeaders.DROP_HEADER)) { continue; }/* w w w. j ava2 s . c o m*/ if (valueSettings.equals(RequestHeaders.DYNAMIC_HEADER)) { if (name.equals("user-agent") && valuesIn != null && !valuesIn.isEmpty()) { req.addHeader(nameProperCase, settings.userAgentString()); } else if (name.equals("host")) { req.addHeader(nameProperCase, hostHeader()); } else if (valuesIn != null && !valuesIn.isEmpty()) { for (String curVal : valuesIn) { req.addHeader(nameProperCase, curVal); } } } else { req.addHeader(nameProperCase, valueSettings); } } for (Map.Entry<String, List<String>> entry : reqHeaders.entrySet()) { if (!names.contains(entry.getKey())) { for (String val : entry.getValue()) { req.addHeader(reqHeadersCasing.get(entry.getKey()), val); } } } cookieStore.addCsrfHeaders(settings, req); }