List of usage examples for org.apache.http.client.methods HttpUriRequest addHeader
void addHeader(String str, String str2);
From source file:org.apache.camel.component.olingo2.api.impl.Olingo2AppImpl.java
/** * public for unit test, not to be used otherwise *//* ww w . j a v a 2 s .c o m*/ public void execute(HttpUriRequest httpUriRequest, ContentType contentType, FutureCallback<HttpResponse> callback) { // add accept header when its not a form or multipart final String contentTypeString = contentType.toString(); if (!ContentType.APPLICATION_FORM_URLENCODED.getMimeType().equals(contentType.getMimeType()) && !contentType.getMimeType().startsWith(MULTIPART_MIME_TYPE)) { // otherwise accept what is being sent httpUriRequest.addHeader(HttpHeaders.ACCEPT, contentTypeString); } // is something being sent? if (httpUriRequest instanceof HttpEntityEnclosingRequestBase && httpUriRequest.getFirstHeader(HttpHeaders.CONTENT_TYPE) == null) { httpUriRequest.addHeader(HttpHeaders.CONTENT_TYPE, contentTypeString); } // set user specified custom headers if (httpHeaders != null && !httpHeaders.isEmpty()) { for (Map.Entry<String, String> entry : httpHeaders.entrySet()) { httpUriRequest.setHeader(entry.getKey(), entry.getValue()); } } // add client protocol version if not specified if (!httpUriRequest.containsHeader(ODataHttpHeaders.DATASERVICEVERSION)) { httpUriRequest.addHeader(ODataHttpHeaders.DATASERVICEVERSION, ODataServiceVersion.V20); } if (!httpUriRequest.containsHeader(MAX_DATA_SERVICE_VERSION)) { httpUriRequest.addHeader(MAX_DATA_SERVICE_VERSION, ODataServiceVersion.V30); } // execute request client.execute(httpUriRequest, callback); }
From source file:org.openhim.mediator.engine.MediatorServerTest.java
private CloseableHttpResponse executeHTTPRequest(String method, String path, String body, Map<String, String> headers, Map<String, String> params) throws URISyntaxException, IOException { URIBuilder builder = new URIBuilder().setScheme("http").setHost(testConfig.getServerHost()) .setPort(testConfig.getServerPort()).setPath(path); if (params != null) { Iterator<String> iter = params.keySet().iterator(); while (iter.hasNext()) { String param = iter.next(); builder.addParameter(param, params.get(param)); }// w ww .ja v a2 s . c om } HttpUriRequest uriReq; switch (method) { case "GET": uriReq = new HttpGet(builder.build()); break; case "POST": uriReq = new HttpPost(builder.build()); StringEntity entity = new StringEntity(body); if (body.length() > 1024) { //always test big requests chunked entity.setChunked(true); } ((HttpPost) uriReq).setEntity(entity); break; case "PUT": uriReq = new HttpPut(builder.build()); StringEntity putEntity = new StringEntity(body); ((HttpPut) uriReq).setEntity(putEntity); break; case "DELETE": uriReq = new HttpDelete(builder.build()); break; default: throw new UnsupportedOperationException(method + " requests not supported"); } if (headers != null) { Iterator<String> iter = headers.keySet().iterator(); while (iter.hasNext()) { String header = iter.next(); uriReq.addHeader(header, headers.get(header)); } } RequestConfig.Builder reqConf = RequestConfig.custom().setConnectTimeout(1000) .setConnectionRequestTimeout(1000); CloseableHttpClient client = HttpClientBuilder.create().setDefaultRequestConfig(reqConf.build()).build(); CloseableHttpResponse response = client.execute(uriReq); boolean foundContentType = false; for (Header hdr : response.getAllHeaders()) { if ("content-type".equalsIgnoreCase(hdr.getName())) { assertTrue(hdr.getValue().contains("application/json+openhim")); foundContentType = true; } } assertTrue("Content-Type must be included in the response", foundContentType); return response; }
From source file:edu.umich.ctools.sectionsUtilityTool.SectionsUtilityToolServlet.java
private HttpResponse processApiCall(HttpUriRequest clientRequest) { HttpClient client = new DefaultHttpClient(); final ArrayList<NameValuePair> nameValues = new ArrayList<NameValuePair>(); nameValues.add(new BasicNameValuePair("Authorization", "Bearer" + " " + canvasToken)); nameValues.add(new BasicNameValuePair("content-type", "application/json")); for (final NameValuePair h : nameValues) { clientRequest.addHeader(h.getName(), h.getValue()); }// w w w . java 2s .c om HttpResponse response = null; long startTime = System.currentTimeMillis(); try { response = client.execute(clientRequest); } catch (IOException e) { M_log.error("Canvas API call did not complete successfully", e); } long stopTime = System.currentTimeMillis(); long elapsedTime = stopTime - startTime; M_log.info(String.format("CANVAS Api response took %sms", elapsedTime)); return response; }
From source file:com.bigdata.journal.jini.ha.AbstractHAJournalServerTestCase.java
/** * Http connection.// w w w .jav a2s.c om * * @param opts * The connection options. * * @return The connection. */ protected HttpResponse doConnect(final HttpClient httpClient, final ConnectOptions opts) throws Exception { /* * Generate the fully formed and encoded URL. */ final StringBuilder urlString = new StringBuilder(opts.serviceURL); ConnectOptions.addQueryParams(urlString, opts.requestParams); if (log.isDebugEnabled()) { log.debug("*** Request ***"); log.debug(opts.serviceURL); log.debug(opts.method); log.debug("query=" + opts.getRequestParam("query")); } HttpUriRequest request = null; try { request = newRequest(urlString.toString(), opts.method); if (opts.requestHeaders != null) { for (Map.Entry<String, String> e : opts.requestHeaders.entrySet()) { request.addHeader(e.getKey(), e.getValue()); if (log.isDebugEnabled()) log.debug(e.getKey() + ": " + e.getValue()); } } if (opts.entity != null) { ((HttpEntityEnclosingRequestBase) request).setEntity(opts.entity); } final HttpResponse response = httpClient.execute(request); return response; // // connect. // conn.connect(); // // return conn; } catch (Throwable t) { /* * If something goes wrong, then close the http connection. * Otherwise, the connection will be closed by the caller. */ try { if (request != null) request.abort(); // // clean up the connection resources // if (conn != null) // conn.disconnect(); } catch (Throwable t2) { // ignored. } throw new RuntimeException(opts.serviceURL + " : " + t, t); } }
From source file:org.fedoraproject.copr.client.impl.RpcCommand.java
public T execute(DefaultCoprSession session) throws CoprException { try {//from www . ja va2 s . co m HttpClient client = session.getClient(); String baseUrl = session.getConfiguration().getUrl(); String commandUrl = getCommandUrl(); String url = baseUrl + commandUrl; Map<String, String> extraArgs = getExtraArguments(); HttpUriRequest request; if (extraArgs == null) { request = new HttpGet(url); } else { HttpPost post = new HttpPost(url); request = post; List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); for (Entry<String, String> entry : extraArgs.entrySet()) { nameValuePairs.add(new BasicNameValuePair(entry.getKey(), entry.getValue())); } post.setEntity(new UrlEncodedFormEntity(nameValuePairs)); } if (requiresAuthentication()) { String login = session.getConfiguration().getLogin(); if (login == null || login.isEmpty()) throw new CoprException("Authentification is required to perform this command " + "but no login was provided in configuration"); String token = session.getConfiguration().getToken(); if (token == null || token.isEmpty()) throw new CoprException("Authentification is required to perform this command " + "but no login was provided in configuration"); String auth = login + ":" + token; String encodedAuth = DatatypeConverter.printBase64Binary(auth.getBytes(StandardCharsets.UTF_8)); request.setHeader("Authorization", "Basic " + encodedAuth); } request.addHeader("Accept", APPLICATION_JSON.getMimeType()); HttpResponse response = client.execute(request); int returnCode = response.getStatusLine().getStatusCode(); if (returnCode != HttpURLConnection.HTTP_OK) { throw new CoprException( "Copr RPC failed: HTTP " + returnCode + " " + response.getStatusLine().getReasonPhrase()); } Reader responseReader = new InputStreamReader(response.getEntity().getContent()); JsonParser parser = new JsonParser(); JsonObject rpcResponse = parser.parse(responseReader).getAsJsonObject(); String rpcStatus = rpcResponse.get("output").getAsString(); if (!rpcStatus.equals("ok")) { throw new CoprException("Copr RPC returned failure reponse"); } return parseResponse(rpcResponse); } catch (IOException e) { throw new CoprException("Failed to call remote Copr procedure", e); } }
From source file:com.csipsimple.service.DownloadLibService.java
private boolean downloadFile(RemoteLibInfo updateInfo) throws IOException { HttpClient httpClient = new DefaultHttpClient(); HttpClient MD5httpClient = new DefaultHttpClient(); HttpUriRequest req, md5req; HttpResponse response, md5response;//from w ww.j a v a2 s . c o m URI updateURI; File destinationFile = null; File partialDestinationFile = null; String downloadedMD5 = null; String fileName = updateInfo.getFileName(); File filePath = updateInfo.getFilePath(); // Set the Filename to update.zip.partial partialDestinationFile = new File(filePath, fileName + ".part"); destinationFile = new File(filePath, fileName + ".gz"); if (partialDestinationFile.exists()) { partialDestinationFile.delete(); } if (!cancellingDownload) { updateURI = updateInfo.getDownloadUri(); boolean md5Available = true; try { req = new HttpGet(updateURI); md5req = new HttpGet(updateURI + ".md5sum"); // Add no-cache Header, so the File gets downloaded each time req.addHeader("Cache-Control", "no-cache"); md5req.addHeader("Cache-Control", "no-cache"); //Proceed request md5response = MD5httpClient.execute(md5req); response = httpClient.execute(req); //Get responses codes int serverResponse = response.getStatusLine().getStatusCode(); int md5serverResponse = md5response.getStatusLine().getStatusCode(); if (md5serverResponse != HttpStatus.SC_OK) { md5Available = false; } if (serverResponse == HttpStatus.SC_OK) { if (md5Available) { //Get the md5 sum and save it into a string try { HttpEntity temp = md5response.getEntity(); InputStreamReader isr = new InputStreamReader(temp.getContent()); BufferedReader br = new BufferedReader(isr); try { downloadedMD5 = br.readLine().split(" ")[0]; } catch (NullPointerException e) { md5Available = false; } br.close(); isr.close(); if (temp != null) { temp.consumeContent(); } } catch (IOException e) { //Nothing to do, just imagine there is a problem with download md5Available = false; } } // Download Update ZIP if md5sum went ok HttpEntity entity = response.getEntity(); dumpFile(entity, partialDestinationFile, destinationFile); //Will cancel download if (cancellingDownload) { mToastHandler .sendMessage(mToastHandler.obtainMessage(0, R.string.unable_to_download_file, 0)); return false; } if (entity != null && !cancellingDownload) { entity.consumeContent(); } else { entity = null; } if (md5Available) { if (!MD5.checkMD5(downloadedMD5, destinationFile)) { throw new IOException("md5_verification_failed"); } } return true; } } catch (IOException ex) { mToastHandler.sendMessage(mToastHandler.obtainMessage(0, ex.getMessage())); } if (Thread.currentThread().isInterrupted() || !Thread.currentThread().isAlive()) { mToastHandler.sendMessage(mToastHandler.obtainMessage(0, R.string.unable_to_download_file, 0)); return false; } } mToastHandler.sendMessage(mToastHandler.obtainMessage(0, R.string.unable_to_download_file, 0)); return false; }
From source file:de.taimos.httputils.HTTPRequest.java
private HttpResponse execute(final HttpUriRequest req) { final HttpClientBuilder builder = HttpClientBuilder.create(); final Builder reqConfig = RequestConfig.custom(); if (this.timeout != null) { reqConfig.setConnectTimeout(this.timeout); }/*from w w w . j a v a 2 s . c o m*/ reqConfig.setRedirectsEnabled(this.followRedirect); builder.setDefaultRequestConfig(reqConfig.build()); if ((this.userAgent != null) && !this.userAgent.isEmpty()) { builder.setUserAgent(this.userAgent); } try { final CloseableHttpClient httpclient = builder.build(); // if request has data populate body if (req instanceof HttpEntityEnclosingRequestBase) { final HttpEntityEnclosingRequestBase entityBase = (HttpEntityEnclosingRequestBase) req; entityBase.setEntity(new StringEntity(this.body, "UTF-8")); } // Set headers final Set<Entry<String, List<String>>> entrySet = this.headers.entrySet(); for (final Entry<String, List<String>> entry : entrySet) { final List<String> list = entry.getValue(); for (final String string : list) { req.addHeader(entry.getKey(), string); } } final HttpResponse response = httpclient.execute(req); return response; } catch (final ClientProtocolException e) { throw new RuntimeException(e); } catch (final IOException e) { throw new RuntimeException(e); } }
From source file:org.opens.urlmanager.it.utils.AHttpRequestBasedTest.java
protected HttpResponse doRequest(String subURL, HttpMethod method, Map<String, String> header, Map<String, String> parameters) throws Exception { HttpClient httpClient = new DefaultHttpClient(); try {/* ww w . j ava 2 s .c om*/ Iterator<Entry<String, String>> it; HttpUriRequest httpRequest; // create URL String url = BASE_URL + subURL; if (method == HttpMethod.GET) { // append parameters in case of a GET request if (parameters != null) { url = appendParametersToURL(url, parameters); } httpRequest = (HttpUriRequest) new HttpGet(url); } else { // in case of a post request, fill request body with the parameters HttpPost httpPost = new HttpPost(url); if (parameters != null) { List<NameValuePair> nvps = new ArrayList<NameValuePair>(parameters.size()); // fill up entity (body) it = parameters.entrySet().iterator(); while (it.hasNext()) { Entry<String, String> entry = it.next(); assert (entry.getKey() != null); assert (entry.getValue() != null); nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue())); } httpPost.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8")); } httpRequest = httpPost; } // fill up header it = header.entrySet().iterator(); while (it.hasNext()) { Entry<String, String> entry = it.next(); httpRequest.addHeader(entry.getKey(), entry.getValue()); } // execute query HttpResponse response = httpClient.execute(httpRequest); return response; } finally { // FIXME: should be done :3 //httpClient.getConnectionManager().shutdown(); } }
From source file:com.corebase.android.framework.http.client.AsyncHttpClient.java
/** * Perform a HTTP GET request and track the Android Context which initiated * the request with customized headers//from w w w. java2s. c om * * @param url * the URL to send the request to. * @param headers * set headers only for this request * @param params * additional GET parameters to send with the request. * @param responseHandler * the response handler instance that should handle the response. */ public void get(Context context, String url, Map<String, String> clientHeaderMap, RequestParams params, CacheParams cacheParams, AsyncHttpResponseHandler responseHandler) { HttpUriRequest request = null; if (null == url || "".equals(url)) return; try { request = new HttpGet(getUrlWithQueryString(url, params)); } catch (IllegalArgumentException e) { responseHandler.sendFailureMessage(context, e, "uri is invalid"); e.printStackTrace(); return; } if (clientHeaderMap != null && clientHeaderMap.size() > 0) { for (String header : clientHeaderMap.keySet()) { request.addHeader(header, clientHeaderMap.get(header)); } } setTimeout(socketTimeout); // if(headers != null) request.setHeaders(headers); sendRequest(httpClient, httpContext, request, null, cacheParams, responseHandler, context); }