List of usage examples for org.apache.http.client.methods HttpRequestBase setHeader
public void setHeader(String str, String str2)
From source file:net.smartam.leeloo.httpclient4.HttpClient4.java
public <T extends OAuthClientResponse> T execute(OAuthClientRequest request, Map<String, String> headers, String requestMethod, Class<T> responseClass) throws OAuthSystemException, OAuthProblemException { try {/*www . j av a 2 s. c o m*/ URI location = new URI(request.getLocationUri()); HttpRequestBase req = null; String responseBody = ""; if (!OAuthUtils.isEmpty(requestMethod) && OAuth.HttpMethod.POST.equals(requestMethod)) { req = new HttpPost(location); HttpEntity entity = new StringEntity(request.getBody()); ((HttpPost) req).setEntity(entity); } else { req = new HttpGet(location); } if (headers != null && !headers.isEmpty()) { for (Map.Entry<String, String> header : headers.entrySet()) { req.setHeader(header.getKey(), header.getValue()); } } HttpResponse response = client.execute(req); Header contentTypeHeader = null; HttpEntity entity = response.getEntity(); if (entity != null) { responseBody = EntityUtils.toString(entity); contentTypeHeader = entity.getContentType(); } String contentType = null; if (contentTypeHeader != null) { contentType = contentTypeHeader.toString(); } return OAuthClientResponseFactory.createCustomResponse(responseBody, contentType, response.getStatusLine().getStatusCode(), responseClass); } catch (Exception e) { throw new OAuthSystemException(e); } }
From source file:org.herrlado.engeo.Utils.java
/** * Get a fresh HTTP-Connection./*from w ww. j a va 2 s .co m*/ * * @param url * URL to open * @param cookies * cookies to transmit * @param postData * post data * @param userAgent * user agent * @param referer * referer * @param encoding * encoding; default encoding: ISO-8859-15 * @param trustAll * trust all SSL certificates; only used on first call! * @param knownFingerprints * fingerprints that are known to be valid; only used on first * call! Only used if {@code trustAll == false} * @return the connection * @throws IOException * IOException */ private static HttpResponse getHttpClient(final String url, final ArrayList<Cookie> cookies, final ArrayList<BasicNameValuePair> postData, final String userAgent, final String referer, final String encoding, final boolean trustAll, final String... knownFingerprints) throws IOException { Log.d(TAG, "HTTPClient URL: " + url); SchemeRegistry registry = null; if (httpClient == null) { if (trustAll || (// . knownFingerprints != null && // . knownFingerprints.length > 0)) { registry = new SchemeRegistry(); registry.register(new Scheme("http", new PlainSocketFactory(), PORT_HTTP)); // final FakeSocketFactory httpsSocketFactory; // if (trustAll) { // httpsSocketFactory = new FakeSocketFactory(); // } else { // httpsSocketFactory = new FakeSocketFactory( // knownFingerprints); // } // registry.register(new Scheme("https", httpsSocketFactory, // PORT_HTTPS)); HttpParams params = new BasicHttpParams(); httpClient = new DefaultHttpClient(new ThreadSafeClientConnManager(params, registry), params); } else { httpClient = new DefaultHttpClient(); } httpClient.addResponseInterceptor(new HttpResponseInterceptor() { @Override public void process(final HttpResponse response, final HttpContext context) throws HttpException, IOException { HttpEntity entity = response.getEntity(); Header contentEncodingHeader = entity.getContentEncoding(); if (contentEncodingHeader != null) { HeaderElement[] codecs = contentEncodingHeader.getElements(); for (int i = 0; i < codecs.length; i++) { if (codecs[i].getName().equalsIgnoreCase(GZIP)) { response.setEntity(new GzipDecompressingEntity(response.getEntity())); return; } } } } }); } if (cookies != null && cookies.size() > 0) { final int l = cookies.size(); CookieStore cs = httpClient.getCookieStore(); for (int i = 0; i < l; i++) { cs.addCookie(cookies.get(i)); } } Log.d(TAG, getCookies(httpClient)); HttpRequestBase request; if (postData == null) { request = new HttpGet(url); } else { HttpPost pr = new HttpPost(url); if (encoding != null && encoding.length() > 0) { pr.setEntity(new UrlEncodedFormEntity(postData, encoding)); } else { pr.setEntity(new UrlEncodedFormEntity(postData, "ISO-8859-15")); } // Log.d(TAG, "HTTPClient POST: " + postData); request = pr; } request.addHeader(ACCEPT_ENCODING, GZIP); if (referer != null) { request.setHeader("Referer", referer); // Log.d(TAG, "HTTPClient REF: " + referer); } if (userAgent != null) { request.setHeader("User-Agent", userAgent); // Log.d(TAG, "HTTPClient AGENT: " + userAgent); } // Log.d(TAG, getHeaders(request)); return httpClient.execute(request); }
From source file:org.apache.oltu.oauth2.httpclient4.HttpClient4.java
public <T extends OAuthClientResponse> T execute(OAuthClientRequest request, Map<String, String> headers, String requestMethod, Class<T> responseClass) throws OAuthSystemException, OAuthProblemException { try {//w w w. j av a 2 s . c o m URI location = new URI(request.getLocationUri()); HttpRequestBase req = null; String responseBody = ""; if (!OAuthUtils.isEmpty(requestMethod) && OAuth.HttpMethod.POST.equals(requestMethod)) { req = new HttpPost(location); HttpEntity entity = new StringEntity(request.getBody()); ((HttpPost) req).setEntity(entity); } else { req = new HttpGet(location); } if (headers != null && !headers.isEmpty()) { for (Map.Entry<String, String> header : headers.entrySet()) { req.setHeader(header.getKey(), header.getValue()); } } if (request.getHeaders() != null) { for (Map.Entry<String, String> header : request.getHeaders().entrySet()) { req.setHeader(header.getKey(), header.getValue()); } } HttpResponse response = client.execute(req); Header contentTypeHeader = null; HttpEntity entity = response.getEntity(); if (entity != null) { responseBody = EntityUtils.toString(entity); contentTypeHeader = entity.getContentType(); } String contentType = null; if (contentTypeHeader != null) { contentType = contentTypeHeader.toString(); } return OAuthClientResponseFactory.createCustomResponse(responseBody, contentType, response.getStatusLine().getStatusCode(), responseClass); } catch (Exception e) { throw new OAuthSystemException(e); } }
From source file:com.dongfang.net.http.HttpHandler.java
@SuppressWarnings("unchecked") private ResponseInfo<T> sendRequest(HttpRequestBase request) throws HttpException { if (autoResume && isDownloadingFile) { File downloadFile = new File(fileSavePath); long fileLen = 0; if (downloadFile.isFile() && downloadFile.exists()) { fileLen = downloadFile.length(); }/*from www. java 2 s . c o m*/ if (fileLen > 0) { request.setHeader("RANGE", "bytes=" + fileLen + "-"); } } boolean retry = true; HttpRequestRetryHandler retryHandler = client.getHttpRequestRetryHandler(); while (retry) { IOException exception = null; try { // ?? // if (request.getMethod().equals(HttpRequest.HttpMethod.GET.toString())) { // String result = HttpUtils.sHttpGetCache.get(requestUrl); // if (result != null) { // return new ResponseInfo<T>(null, (T) result, true); // } // } ResponseInfo<T> responseInfo = null; if (!isCancelled()) { HttpResponse response = client.execute(request, context); responseInfo = handleResponse(response); } return responseInfo; } catch (UnknownHostException e) { exception = e; retry = retryHandler.retryRequest(exception, ++retriedTimes, context); } catch (IOException e) { exception = e; retry = retryHandler.retryRequest(exception, ++retriedTimes, context); } catch (NullPointerException e) { exception = new IOException(e.getMessage()); exception.initCause(e); retry = retryHandler.retryRequest(exception, ++retriedTimes, context); } catch (HttpException e) { throw e; } catch (Throwable e) { exception = new IOException(e.getMessage()); exception.initCause(e); retry = retryHandler.retryRequest(exception, ++retriedTimes, context); } if (!retry && exception != null) { throw new HttpException(exception); } } return null; }
From source file:com.yahoo.gondola.container.client.ApacheHttpComponentProxyClient.java
private CloseableHttpResponse executeRequest(HttpRequestBase httpRequest, ContainerRequestContext request) throws IOException { CloseableHttpResponse proxiedResponse; // Forward all the headers for (Map.Entry<String, List<String>> e : request.getHeaders().entrySet()) { for (String headerValue : e.getValue()) { // TODO: Should have a safer way to treat some non-forwardable header. if (e.getKey().equalsIgnoreCase("Content-Length") || e.getKey().equalsIgnoreCase("Transfer-Encoding")) { continue; }//from ww w . ja v a2 s . c o m httpRequest.setHeader(e.getKey(), headerValue); } } if (httpRequest instanceof HttpEntityEnclosingRequest) { Object requestBody = request.getProperty("requestBody"); if (requestBody == null) { requestBody = IOUtils.toString(request.getEntityStream()); request.setProperty("requestBody", requestBody); } ((HttpEntityEnclosingRequest) httpRequest).setEntity(new StringEntity((String) requestBody)); } proxiedResponse = httpClient.execute(httpRequest); return proxiedResponse; }
From source file:com.domuslink.communication.ApiHandler.java
/** * Pull the raw text content of the given URL. This call blocks until the * operation has completed, and is synchronized because it uses a shared * buffer {@link #sBuffer}./*w w w .j a v a 2 s . c om*/ * * @param type The type of either a GET or POST for the request * @param commandURI The constructed URI for the path * @return The raw content returned by the server. * @throws ApiException If any connection or server error occurs. */ protected static synchronized String urlContent(int type, URI commandURI, ApiCookieHandler cookieHandler) throws ApiException { HttpResponse response; HttpRequestBase request; if (sUserAgent == null) { throw new ApiException("User-Agent string must be prepared"); } // Create client and set our specific user-agent string DefaultHttpClient client = new DefaultHttpClient(); UsernamePasswordCredentials creds = new UsernamePasswordCredentials("", sPassword); CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT), creds); client.setCredentialsProvider(credsProvider); CookieStore cookieStore = cookieHandler.getCookieStore(); if (cookieStore != null) { boolean expiredCookies = false; Date nowTime = new Date(); for (Cookie theCookie : cookieStore.getCookies()) { if (theCookie.isExpired(nowTime)) expiredCookies = true; } if (!expiredCookies) client.setCookieStore(cookieStore); else { cookieHandler.setCookieStore(null); cookieStore = null; } } try { if (type == POST_TYPE) request = new HttpPost(commandURI); else request = new HttpGet(commandURI); request.setHeader("User-Agent", sUserAgent); response = client.execute(request); // Check if server response is valid StatusLine status = response.getStatusLine(); if (status.getStatusCode() != HTTP_STATUS_OK) { Log.e(TAG, "urlContent: Url issue: " + commandURI.toString() + " with status: " + status.toString()); throw new ApiException("Invalid response from server: " + status.toString()); } // Pull content stream from response HttpEntity entity = response.getEntity(); InputStream inputStream = entity.getContent(); ByteArrayOutputStream content = new ByteArrayOutputStream(); // Read response into a buffered stream int readBytes = 0; while ((readBytes = inputStream.read(sBuffer)) != -1) { content.write(sBuffer, 0, readBytes); } if (cookieStore == null) { List<Cookie> realCookies = client.getCookieStore().getCookies(); if (!realCookies.isEmpty()) { BasicCookieStore newCookies = new BasicCookieStore(); for (int i = 0; i < realCookies.size(); i++) { newCookies.addCookie(realCookies.get(i)); // Log.d(TAG, "aCookie - " + realCookies.get(i).toString()); } cookieHandler.setCookieStore(newCookies); } } // Return result from buffered stream return content.toString(); } catch (IOException e) { Log.e(TAG, "urlContent: client execute: " + commandURI.toString()); throw new ApiException("Problem communicating with API", e); } catch (IllegalArgumentException e) { Log.e(TAG, "urlContent: client execute: " + commandURI.toString()); throw new ApiException("Problem communicating with API", e); } finally { // When HttpClient instance is no longer needed, // shut down the connection manager to ensure // immediate deallocation of all system resources client.getConnectionManager().shutdown(); } }
From source file:com.mobeelizer.java.connection.MobeelizerConnectionServiceImpl.java
private void setHeaders(final HttpRequestBase request, final boolean setJsonContentType, final boolean setUserPassword) { if (setJsonContentType) { request.setHeader("content-type", "application/json"); }//from w ww .j a v a 2s.c om request.setHeader("mas-vendor-name", delegate.getVendor()); request.setHeader("mas-application-name", delegate.getApplication()); request.setHeader("mas-application-instance-name", delegate.getInstance()); request.setHeader("mas-definition-digest", delegate.getVersionDigest()); request.setHeader("mas-device-name", delegate.getDevice()); request.setHeader("mas-device-identifier", delegate.getDeviceIdentifier()); if (setUserPassword) { request.setHeader("mas-user-name", delegate.getUser()); request.setHeader("mas-user-password", delegate.getPassword()); } request.setHeader("mas-sdk-version", delegate.getSdkVersion()); }
From source file:com.intuit.tank.httpclient4.TankHttpClient4.java
/** * Set all the header keys//from w w w .j a va2s . c om * * @param connection */ @SuppressWarnings("rawtypes") private void setHeaders(BaseRequest request, HttpRequestBase method, HashMap<String, String> headerInformation) { try { Set set = headerInformation.entrySet(); Iterator iter = set.iterator(); while (iter.hasNext()) { Map.Entry mapEntry = (Map.Entry) iter.next(); method.setHeader((String) mapEntry.getKey(), (String) mapEntry.getValue()); } } catch (Exception ex) { LOG.warn(request.getLogUtil().getLogMessage("Unable to set header: " + ex.getMessage(), LogEventType.System)); } }
From source file:com.heaptrip.util.http.bixo.fetcher.SimpleHttpFetcher.java
public FetchedResult get(String url, List<TupleTwo<?, ?>> headers) throws BaseFetchException { HttpRequestBase request = new HttpGet(); request.setHeader("User-Agent", _userAgent.getUserAgentString()); return fetch(request, url, null, headers); }
From source file:com.heaptrip.util.http.bixo.fetcher.SimpleHttpFetcher.java
public FetchedResult post(String url, List<TupleTwo<?, ?>> data, List<TupleTwo<?, ?>> headers) throws BaseFetchException { HttpRequestBase request = new HttpPost(); request.setHeader("User-Agent", _userAgent.getUserAgentString()); return fetch(request, url, data, headers); }