List of usage examples for org.apache.http.client.methods HttpUriRequest addHeader
void addHeader(String str, String str2);
From source file:com.my.cloudcontact.http.FinalHttp.java
protected <T> void sendRequest(DefaultHttpClient client, HttpContext httpContext, HttpUriRequest uriRequest, String contentType, AjaxCallBack<T> ajaxCallBack) { if (contentType != null) { uriRequest.addHeader("Content-Type", contentType); // for (String header : clientHeaderMap.keySet()) { // initClientHeader(requestHeader); // uriRequest.addHeader(header, clientHeaderMap.get(header)); // } }/* w w w . j a va 2 s . c o m*/ requestHeader.addHeaders(uriRequest, requestHeader); new HttpHandler<T>(client, httpContext, ajaxCallBack, charset).executeOnExecutor(executor, uriRequest); }
From source file:org.envirocar.app.dao.remote.BaseRemoteDAO.java
private HttpResponse executeHttpRequest(HttpUriRequest request) throws NotConnectedException { if (this instanceof AuthenticatedDAO) { User user = UserManager.instance().getUser(); if (user != null && user.getUsername() != null && user.getToken() != null) { request.addHeader("X-User", user.getUsername()); request.addHeader("X-Token", user.getToken()); }//from w w w . ja v a 2 s . c o m } if (!request.containsHeader("Accept-Encoding")) { request.addHeader("Accept-Encoding", "gzip"); } /* * TODO enable client-site gzip if server responeded with that at least once! */ HttpResponse result; try { result = HTTPClient.execute(request); } catch (IOException e) { throw new NotConnectedException(e); } return result; }
From source file:br.com.bioscada.apps.biotracks.io.gdata.AndroidGDataClient.java
private InputStream createAndExecuteMethod(HttpRequestCreator creator, String uriString, String authToken) throws HttpException, IOException { HttpResponse response = null;/*from w w w. j a v a2s.c om*/ int status = 500; int redirectsLeft = MAX_REDIRECTS; URI uri; try { uri = new URI(uriString); } catch (URISyntaxException use) { Log.w(TAG, "Unable to parse " + uriString + " as URI.", use); throw new IOException("Unable to parse " + uriString + " as URI: " + use.getMessage()); } // we follow redirects ourselves, since we want to follow redirects even on // POSTs, which // the HTTP library does not do. following redirects ourselves also allows // us to log // the redirects using our own logging. while (redirectsLeft > 0) { HttpUriRequest request = creator.createRequest(uri); request.addHeader("User-Agent", "Android-GData"); request.addHeader("Accept-Encoding", "gzip"); // only add the auth token if not null (to allow for GData feeds that do // not require // authentication.) if (!TextUtils.isEmpty(authToken)) { request.addHeader("Authorization", "GoogleLogin auth=" + authToken); } if (DEBUG) { for (Header h : request.getAllHeaders()) { Log.v(TAG, h.getName() + ": " + h.getValue()); } Log.d(TAG, "Executing " + request.getRequestLine().toString()); } response = null; try { response = httpClient.execute(request); } catch (IOException ioe) { Log.w(TAG, "Unable to execute HTTP request." + ioe); throw ioe; } StatusLine statusLine = response.getStatusLine(); if (statusLine == null) { Log.w(TAG, "StatusLine is null."); throw new NullPointerException("StatusLine is null -- should not happen."); } if (Log.isLoggable(TAG, Log.DEBUG)) { Log.d(TAG, response.getStatusLine().toString()); for (Header h : response.getAllHeaders()) { Log.d(TAG, h.getName() + ": " + h.getValue()); } } status = statusLine.getStatusCode(); HttpEntity entity = response.getEntity(); if ((status >= 200) && (status < 300) && entity != null) { return getUngzippedContent(entity); } // TODO: handle 301, 307? // TODO: let the http client handle the redirects, if we can be sure we'll // never get a // redirect on POST. if (status == 302) { // consume the content, so the connection can be closed. entity.consumeContent(); Header location = response.getFirstHeader("Location"); if (location == null) { if (Log.isLoggable(TAG, Log.DEBUG)) { Log.d(TAG, "Redirect requested but no Location " + "specified."); } break; } if (Log.isLoggable(TAG, Log.DEBUG)) { Log.d(TAG, "Following redirect to " + location.getValue()); } try { uri = new URI(location.getValue()); } catch (URISyntaxException use) { if (Log.isLoggable(TAG, Log.DEBUG)) { Log.d(TAG, "Unable to parse " + location.getValue() + " as URI.", use); throw new IOException("Unable to parse " + location.getValue() + " as URI."); } break; } --redirectsLeft; } else { break; } } if (Log.isLoggable(TAG, Log.VERBOSE)) { Log.v(TAG, "Received " + status + " status code."); } String errorMessage = null; HttpEntity entity = response.getEntity(); try { if (entity != null) { InputStream in = entity.getContent(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] buf = new byte[8192]; int bytesRead = -1; while ((bytesRead = in.read(buf)) != -1) { baos.write(buf, 0, bytesRead); } // TODO: use appropriate encoding, picked up from Content-Type. errorMessage = new String(baos.toByteArray()); if (Log.isLoggable(TAG, Log.VERBOSE)) { Log.v(TAG, errorMessage); } } } finally { if (entity != null) { entity.consumeContent(); } } String exceptionMessage = "Received " + status + " status code"; if (errorMessage != null) { exceptionMessage += (": " + errorMessage); } throw new HttpException(exceptionMessage, status, null /* InputStream */); }
From source file:jp.yojio.triplog.Common.DataApi.gdata.AndroidGDataClient.java
private InputStream createAndExecuteMethod(HttpRequestCreator creator, String uriString, String authToken) throws HttpException, IOException { HttpResponse response = null;// w w w . j a va 2 s.c o m int status = 500; int redirectsLeft = MAX_REDIRECTS; URI uri; try { uri = new URI(uriString); } catch (URISyntaxException use) { Log.w(TAG, "Unable to parse " + uriString + " as URI.", use); throw new IOException("Unable to parse " + uriString + " as URI: " + use.getMessage()); } // we follow redirects ourselves, since we want to follow redirects even on // POSTs, which // the HTTP library does not do. following redirects ourselves also allows // us to log // the redirects using our own logging. while (redirectsLeft > 0) { HttpUriRequest request = creator.createRequest(uri); request.addHeader("Accept-Encoding", "gzip"); // only add the auth token if not null (to allow for GData feeds that do // not require // authentication.) if (!TextUtils.isEmpty(authToken)) { request.addHeader("Authorization", "GoogleLogin auth=" + authToken); } if (LOCAL_LOGV) { for (Header h : request.getAllHeaders()) { Log.v(TAG, h.getName() + ": " + h.getValue()); } Log.d(TAG, "Executing " + request.getRequestLine().toString()); } response = null; try { response = httpClient.execute(request); } catch (IOException ioe) { Log.w(TAG, "Unable to execute HTTP request." + ioe); throw ioe; } StatusLine statusLine = response.getStatusLine(); if (statusLine == null) { Log.w(TAG, "StatusLine is null."); throw new NullPointerException("StatusLine is null -- should not happen."); } if (Log.isLoggable(TAG, Log.DEBUG)) { Log.d(TAG, response.getStatusLine().toString()); for (Header h : response.getAllHeaders()) { Log.d(TAG, h.getName() + ": " + h.getValue()); } } status = statusLine.getStatusCode(); HttpEntity entity = response.getEntity(); if ((status >= 200) && (status < 300) && entity != null) { return getUngzippedContent(entity); } // TODO: handle 301, 307? // TODO: let the http client handle the redirects, if we can be sure we'll // never get a // redirect on POST. if (status == 302) { // consume the content, so the connection can be closed. entity.consumeContent(); Header location = response.getFirstHeader("Location"); if (location == null) { if (Log.isLoggable(TAG, Log.DEBUG)) { Log.d(TAG, "Redirect requested but no Location " + "specified."); } break; } if (Log.isLoggable(TAG, Log.DEBUG)) { Log.d(TAG, "Following redirect to " + location.getValue()); } try { uri = new URI(location.getValue()); } catch (URISyntaxException use) { if (Log.isLoggable(TAG, Log.DEBUG)) { Log.d(TAG, "Unable to parse " + location.getValue() + " as URI.", use); throw new IOException("Unable to parse " + location.getValue() + " as URI."); } break; } --redirectsLeft; } else { break; } } if (Log.isLoggable(TAG, Log.VERBOSE)) { Log.v(TAG, "Received " + status + " status code."); } String errorMessage = null; HttpEntity entity = response.getEntity(); try { if (response != null && entity != null) { InputStream in = entity.getContent(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] buf = new byte[8192]; int bytesRead = -1; while ((bytesRead = in.read(buf)) != -1) { baos.write(buf, 0, bytesRead); } // TODO: use appropriate encoding, picked up from Content-Type. errorMessage = new String(baos.toByteArray()); if (Log.isLoggable(TAG, Log.VERBOSE)) { Log.v(TAG, errorMessage); } } } finally { if (entity != null) { entity.consumeContent(); } } String exceptionMessage = "Received " + status + " status code"; if (errorMessage != null) { exceptionMessage += (": " + errorMessage); } throw new HttpException(exceptionMessage, status, null /* InputStream */); }
From source file:org.openqa.selenium.remote.internal.ApacheHttpAsyncClient.java
@Override public HttpResponse execute(HttpRequest request, boolean followRedirects) throws IOException { HttpContext context = createContext(); String requestUrl = url.toExternalForm().replaceAll("/$", "") + request.getUri(); HttpUriRequest httpMethod = createHttpUriRequest(request.getMethod(), requestUrl); for (String name : request.getHeaderNames()) { // Skip content length as it is implicitly set when the message entity is set below. if (!"Content-Length".equalsIgnoreCase(name)) { for (String value : request.getHeaders(name)) { httpMethod.addHeader(name, value); }/*from ww w. j a va 2s .c om*/ } } if (httpMethod instanceof HttpPost) { ((HttpPost) httpMethod).setEntity(new ByteArrayEntity(request.getContent())); } client.start(); // start if needed Future<org.apache.http.HttpResponse> future = client.execute(targetHost, httpMethod, context, null); try { org.apache.http.HttpResponse response = future.get(); if (followRedirects) { response = followRedirects(client, context, response, /* redirect count */0); } return createResponse(response, context); } catch (InterruptedException | ExecutionException e) { throw new WebDriverException(e); } }
From source file:org.mule.modules.quickbooks.windows.api.DefaultQuickBooksWindowsClient.java
/** * Returns the list of results pages from QB * /* w w w. jav a 2 s . c o m*/ * @return List of pages with results */ @Override public Iterable findObjectsGetPages(final OAuthCredentials credentials, final WindowsEntityType type, final Object query) { Validate.notNull(type); return new PaginatedIterable<Object, List<Object>>() { private Integer countPage = 1; @Override protected List<Object> firstPage() { return askAnEspecificPage(countPage); } @Override protected boolean hasNextPage(List<Object> arg0) { return arg0.isEmpty(); } @Override protected List<Object> nextPage(List<Object> arg0) { countPage = countPage + 1; return askAnEspecificPage(countPage); } @Override protected Iterator<Object> pageIterator(List<Object> arg0) { return arg0.iterator(); } private List<Object> askAnEspecificPage(Integer pageNumber) { String str = String.format("%s/%s/v2/%s", credentials.getBaseUri(), type.getResouceName(), credentials.getRealmId()); HttpUriRequest httpRequest = new HttpPost(str); httpRequest.addHeader("Content-Type", "text/xml"); ((QueryBase) query).setStartPage(BigInteger.valueOf(pageNumber)); ((QueryBase) query).setChunkSize(getResultsPerPage()); prepareToPost(query, httpRequest); try { Object respObj = makeARequestToQuickbooks(httpRequest, credentials, false); if (respObj instanceof ErrorResponse) { throw new QuickBooksRuntimeException(new ErrorInfo(respObj)); } return getListFromIntuitResponse(respObj, type); } catch (QuickBooksRuntimeException e) { if (e.isAExpiredTokenFault()) { destroyAccessToken(credentials); return askAnEspecificPage(pageNumber); } else { throw e; } } } }; }
From source file:com.fujitsu.dc.test.jersey.DcRestAdapter.java
/** * ????GET.//from w w w.ja va 2 s. co m * @param url URL * @param headers ?? * @return DcResponse * @throws DcException DAO */ public final DcResponse get(final String url, final HashMap<String, String> headers) throws DcException { HttpUriRequest req = new HttpGet(url); for (Map.Entry<String, String> entry : headers.entrySet()) { req.setHeader(entry.getKey(), entry.getValue()); } req.addHeader("X-Dc-Version", DcCoreTestConfig.getCoreVersion()); debugHttpRequest(req, ""); DcResponse res = this.request(req); return res; }
From source file:io.personium.test.jersey.PersoniumRestAdapter.java
/** * ????GET.//from ww w. j a v a 2s .c om * @param url URL * @param headers ?? * @return DcResponse * @throws PersoniumException DAO */ public final PersoniumResponse get(final String url, final HashMap<String, String> headers) throws PersoniumException { HttpUriRequest req = new HttpGet(url); for (Map.Entry<String, String> entry : headers.entrySet()) { req.setHeader(entry.getKey(), entry.getValue()); } req.addHeader("X-Personium-Version", PersoniumCoreTestConfig.getCoreVersion()); debugHttpRequest(req, ""); PersoniumResponse res = this.request(req); return res; }
From source file:org.openqa.selenium.remote.internal.ApacheHttpClient.java
@Override public HttpResponse execute(HttpRequest request, boolean followRedirects) throws IOException { HttpContext context = createContext(); String requestUrl = url.toExternalForm().replaceAll("/$", "") + request.getUri(); HttpUriRequest httpMethod = createHttpUriRequest(request.getMethod(), requestUrl); for (String name : request.getHeaderNames()) { // Skip content length as it is implicitly set when the message entity is set below. if (!"Content-Length".equalsIgnoreCase(name)) { for (String value : request.getHeaders(name)) { httpMethod.addHeader(name, value); }//from w w w . j a v a 2 s . co m } } if (httpMethod instanceof HttpPost) { ((HttpPost) httpMethod).setEntity(new ByteArrayEntity(request.getContent())); } org.apache.http.HttpResponse response = fallBackExecute(context, httpMethod); if (followRedirects) { response = followRedirects(client, context, response, /* redirect count */0); } return createResponse(response, context); }
From source file:com.fujitsu.dc.test.jersey.DcRestAdapter.java
/** * ??? PUT./* w w w.jav a 2 s.co m*/ * @param url URL * @param data ?? * @param headers ?? * @return DcResponse * @throws DcException DAO */ public final DcResponse put(final String url, final String data, final HashMap<String, String> headers) throws DcException { String contentType = headers.get(HttpHeaders.CONTENT_TYPE); HttpUriRequest req = makePutRequest(url, data, contentType); for (Map.Entry<String, String> entry : headers.entrySet()) { req.setHeader(entry.getKey(), entry.getValue()); } req.addHeader("X-Dc-Version", DcCoreTestConfig.getCoreVersion()); debugHttpRequest(req, data); DcResponse res = request(req); return res; }