List of usage examples for org.apache.http.protocol HTTP USER_AGENT
String USER_AGENT
To view the source code for org.apache.http.protocol HTTP USER_AGENT.
Click Source Link
From source file:com.buffalokiwi.api.APIHttpClient.java
/** * Adds the user agent to the request//ww w.j a va 2 s .c om * @return user agent interceptor */ protected HttpRequestInterceptor createUserAgentInterceptor() { return new HttpRequestInterceptor() { @Override public void process(HttpRequest hr, HttpContext hc) throws HttpException, IOException { //..Set the ua header hr.setHeader(HTTP.USER_AGENT, getUserAgent()); } }; }
From source file:com.microsoft.windowsazure.mobileservices.sdk.testapp.test.MobileServiceClientTests.java
public void testOperationShouldAddHeaders() throws Throwable { // Create client MobileServiceClient client = null;/* w ww. ja v a2 s .com*/ try { client = new MobileServiceClient(appUrl, appKey, getInstrumentation().getTargetContext()); } catch (MalformedURLException e) { e.printStackTrace(); } final String expectedAppKey = client.getAppKey(); // Add a new filter to the client client = client.withFilter(new ServiceFilter() { @Override public ListenableFuture<ServiceFilterResponse> handleRequest(ServiceFilterRequest request, NextServiceFilterCallback nextServiceFilterCallback) { final SettableFuture<ServiceFilterResponse> resultFuture = SettableFuture.create(); int zumoInstallationHeaderIndex = -1; int zumoAppHeaderIndex = -1; int zumoVersionHeader = -1; int userAgentHeaderIndex = -1; int acceptHeaderIndex = -1; int acceptEncodingHeaderIndex = -1; String installationHeader = "X-ZUMO-INSTALLATION-ID"; String appHeader = "X-ZUMO-APPLICATION"; String versionHeader = "X-ZUMO-VERSION"; String userAgentHeader = HTTP.USER_AGENT; String acceptHeader = "Accept"; String acceptEncodingHeader = "Accept-Encoding"; String versionNumber = "2.0.2"; Header[] headers = request.getHeaders(); for (int i = 0; i < headers.length; i++) { if (headers[i].getName() == installationHeader) { zumoInstallationHeaderIndex = i; } else if (headers[i].getName() == appHeader) { zumoAppHeaderIndex = i; } else if (headers[i].getName() == versionHeader) { zumoVersionHeader = i; } else if (headers[i].getName() == userAgentHeader) { userAgentHeaderIndex = i; } else if (headers[i].getName() == acceptHeader) { acceptHeaderIndex = i; } else if (headers[i].getName() == acceptEncodingHeader) { acceptEncodingHeaderIndex = i; } } if (zumoInstallationHeaderIndex == -1) { resultFuture.setException(new Exception("zumoInstallationHeaderIndex == -1")); return resultFuture; } if (zumoAppHeaderIndex == -1) { resultFuture.setException(new Exception("zumoAppHeaderIndex == -1")); return resultFuture; } if (zumoVersionHeader == -1) { resultFuture.setException(new Exception("zumoVersionHeader == -1")); return resultFuture; } if (userAgentHeaderIndex == -1) { resultFuture.setException(new Exception("userAgentHeaderIndex == -1")); return resultFuture; } if (acceptHeaderIndex == -1) { resultFuture.setException(new Exception("acceptHeaderIndex == -1")); return resultFuture; } if (acceptEncodingHeaderIndex == -1) { resultFuture.setException(new Exception("acceptEncodingHeaderIndex == -1")); return resultFuture; } String expectedUserAgent = String.format( "ZUMO/%s (lang=%s; os=%s; os_version=%s; arch=%s; version=%s)", "1.0", "Java", "Android", Build.VERSION.RELEASE, Build.CPU_ABI, versionNumber); if (headers[zumoInstallationHeaderIndex].getValue() == null) { resultFuture.setException(new Exception("headers[zumoInstallationHeaderIndex] == null")); return resultFuture; } if (!expectedAppKey.equals(headers[zumoAppHeaderIndex].getValue())) { resultFuture.setException(new Exception("expectedAppKey != headers[zumoAppHeaderIndex]")); return resultFuture; } if (!expectedAppKey.equals(headers[zumoAppHeaderIndex].getValue())) { resultFuture.setException(new Exception("expectedAppKey != headers[zumoAppHeaderIndex]")); return resultFuture; } if (!expectedUserAgent.equals(headers[userAgentHeaderIndex].getValue())) { resultFuture.setException(new Exception("expectedUserAgent != headers[userAgentHeaderIndex]")); return resultFuture; } if (!versionNumber.equals(headers[zumoVersionHeader].getValue())) { resultFuture.setException(new Exception(versionNumber + "!= headers[zumoVersionHeader]")); return resultFuture; } if (!"application/json".equals(headers[acceptHeaderIndex].getValue())) { resultFuture.setException(new Exception("application/json != headers[acceptHeaderIndex]")); return resultFuture; } if (!"gzip".equals(headers[acceptEncodingHeaderIndex].getValue())) { resultFuture.setException(new Exception("gzip != headers[acceptEncodingHeaderIndex]")); return resultFuture; } ServiceFilterResponseMock response = new ServiceFilterResponseMock(); response.setContent("{}"); resultFuture.set(response); return resultFuture; } }); try { client.getTable("dummy").execute().get(); } catch (Exception exception) { if (exception instanceof ExecutionException) { fail(exception.getCause().getMessage()); } else { fail(exception.getMessage()); } } }
From source file:com.connectsdk.service.AirPlayService.java
@Override public void sendCommand(final ServiceCommand<?> serviceCommand) { Util.runInBackground(new Runnable() { @Override//w ww .ja v a 2 s .c o m public void run() { try { StringBuilder sb = new StringBuilder(); sb.append("http://").append(serviceDescription.getIpAddress()).append(":") .append(serviceDescription.getPort()); sb.append(serviceCommand.getTarget()); HttpConnection connection = HttpConnection.newInstance(URI.create(sb.toString())); connection.setHeader(HTTP.USER_AGENT, "ConnectSDK MediaControl/1.0"); connection.setHeader(X_APPLE_SESSION_ID, mSessionId); if (password != null) { String authorization = getAuthenticate(serviceCommand.getHttpMethod(), serviceCommand.getTarget(), authenticate); connection.setHeader("Authorization", authorization); } Object payload = serviceCommand.getPayload(); if (serviceCommand.getHttpMethod().equalsIgnoreCase(ServiceCommand.TYPE_POST) || serviceCommand.getHttpMethod().equalsIgnoreCase(ServiceCommand.TYPE_PUT)) { if (payload != null) { if (payload instanceof String) { connection.setHeader(HttpMessage.CONTENT_TYPE_HEADER, HttpMessage.CONTENT_TYPE_APPLICATION_PLIST); connection.setPayload(payload.toString()); } else if (payload instanceof byte[]) { connection.setPayload((byte[]) payload); } } } if (serviceCommand.getHttpMethod().equalsIgnoreCase(ServiceCommand.TYPE_POST)) { connection.setMethod(HttpConnection.Method.POST); } else if (serviceCommand.getHttpMethod().equalsIgnoreCase(ServiceCommand.TYPE_PUT)) { connection.setMethod(HttpConnection.Method.PUT); } else { connection.setHeader("Content-Length", "0"); } connection.execute(); int code = connection.getResponseCode(); if (code == HttpURLConnection.HTTP_OK) { Util.postSuccess(serviceCommand.getResponseListener(), connection.getResponseString()); } else if (code == HttpURLConnection.HTTP_UNAUTHORIZED) { authenticate = connection.getResponseHeader("WWW-Authenticate"); pendingCommand = serviceCommand; Util.runOnUI(new Runnable() { @Override public void run() { if (listener != null) { listener.onPairingRequired(AirPlayService.this, pairingType, null); } } }); } else { Util.postError(serviceCommand.getResponseListener(), ServiceCommandError.getError(code)); } } catch (IOException e) { e.printStackTrace(); Util.postError(serviceCommand.getResponseListener(), new ServiceCommandError(0, e.getMessage(), null)); } } }); }
From source file:com.clustercontrol.http.util.GetHttpResponse.java
private CloseableHttpClient getHttpClient() throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException { if (m_client == null) { List<Header> headers = new ArrayList<>(); HttpClientBuilder builder = HttpClients.custom().setDefaultCredentialsProvider(m_cledentialProvider) .setDefaultHeaders(headers); if (!this.m_needAuthSSLCert) { // SSL ?? TrustStrategy trustStrategy = new TrustStrategy() { @Override//from ww w . ja v a2 s. co m public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException { return true; } }; builder.setSSLSocketFactory(new SSLConnectionSocketFactory( new SSLContextBuilder().loadTrustMaterial(null, trustStrategy).build(), new NoopHostnameVerifier())); } RequestConfig requestConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.DEFAULT) .setConnectTimeout(m_connectTimeout).setSocketTimeout(m_requestTimeout).build(); builder.setDefaultRequestConfig(requestConfig); if (m_proxyHost != null) { HttpHost proxy = new HttpHost(m_proxyHost, m_proxyPort, m_proxyScheme == null ? "https" : m_proxyScheme); if (m_proxyUser != null && m_proxyPassword != null) { m_cledentialProvider.setCredentials(new AuthScope(proxy.getHostName(), proxy.getPort()), new UsernamePasswordCredentials(m_proxyUser, m_proxyPassword)); } builder.setProxy(proxy); } if (m_userAgent != null) { headers.add(new BasicHeader(HTTP.USER_AGENT, m_userAgent)); } if (m_cancelProxyCache) { // ? // https://www.ipa.go.jp/security/awareness/vendor/programmingv2/contents/405.html headers.add(new BasicHeader("Cache-Control", "no-cache")); headers.add(new BasicHeader("Pragma", "no-cache")); } if (keepAlive) { headers.add(new BasicHeader(HTTP.CONN_DIRECTIVE, HTTP.CONN_KEEP_ALIVE)); } else { headers.add(new BasicHeader(HTTP.CONN_DIRECTIVE, HTTP.CONN_CLOSE)); } m_client = builder.build(); } return m_client; }
From source file:org.apache.maven.wagon.providers.http.AbstractHttpClientWagon.java
protected CloseableHttpResponse execute(HttpUriRequest httpMethod) throws HttpException, IOException { setHeaders(httpMethod);/*from ww w .j ava2s. c om*/ String userAgent = getUserAgent(httpMethod); if (userAgent != null) { httpMethod.setHeader(HTTP.USER_AGENT, userAgent); } RequestConfig.Builder requestConfigBuilder = RequestConfig.custom(); // WAGON-273: default the cookie-policy to browser compatible requestConfigBuilder.setCookieSpec(CookieSpecs.BROWSER_COMPATIBILITY); Repository repo = getRepository(); ProxyInfo proxyInfo = getProxyInfo(repo.getProtocol(), repo.getHost()); if (proxyInfo != null) { HttpHost proxy = new HttpHost(proxyInfo.getHost(), proxyInfo.getPort()); requestConfigBuilder.setProxy(proxy); } HttpMethodConfiguration config = httpConfiguration == null ? null : httpConfiguration.getMethodConfiguration(httpMethod); if (config != null) { ConfigurationUtils.copyConfig(config, requestConfigBuilder); } else { requestConfigBuilder.setSocketTimeout(getReadTimeout()); } localContext.setRequestConfig(requestConfigBuilder.build()); if (config != null && config.isUsePreemptive()) { HttpHost targetHost = new HttpHost(repo.getHost(), repo.getPort(), repo.getProtocol()); AuthScope targetScope = getBasicAuthScope().getScope(targetHost); if (credentialsProvider.getCredentials(targetScope) != null) { BasicScheme targetAuth = new BasicScheme(); targetAuth.processChallenge(new BasicHeader(AUTH.WWW_AUTH, "BASIC preemptive")); authCache.put(targetHost, targetAuth); } } if (proxyInfo != null) { if (proxyInfo.getHost() != null) { HttpHost proxyHost = new HttpHost(proxyInfo.getHost(), proxyInfo.getPort()); AuthScope proxyScope = getProxyBasicAuthScope().getScope(proxyHost); String proxyUsername = proxyInfo.getUserName(); String proxyPassword = proxyInfo.getPassword(); String proxyNtlmHost = proxyInfo.getNtlmHost(); String proxyNtlmDomain = proxyInfo.getNtlmDomain(); if (proxyUsername != null && proxyPassword != null) { Credentials creds; if (proxyNtlmHost != null || proxyNtlmDomain != null) { creds = new NTCredentials(proxyUsername, proxyPassword, proxyNtlmHost, proxyNtlmDomain); } else { creds = new UsernamePasswordCredentials(proxyUsername, proxyPassword); } credentialsProvider.setCredentials(proxyScope, creds); BasicScheme proxyAuth = new BasicScheme(); proxyAuth.processChallenge(new BasicHeader(AUTH.PROXY_AUTH, "BASIC preemptive")); authCache.put(proxyHost, proxyAuth); } } } return CLIENT.execute(httpMethod, localContext); }
From source file:com.rackspacecloud.client.cloudfiles.FilesClient.java
private void setUserAgent(String userAgent) { client.getParams().setParameter(HTTP.USER_AGENT, userAgent); }
From source file:com.rackspacecloud.client.cloudfiles.FilesClient.java
private String getUserAgent() { return client.getParams().getParameter(HTTP.USER_AGENT).toString(); }
From source file:com.newrelic.agent.android.harvest.HarvestConnection.java
public HttpPost createPost(String str, String str2) { String str3 = (str2.length() <= AccessibilityNodeInfoCompat.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY || DISABLE_COMPRESSION_FOR_DEBUGGING.booleanValue()) ? HTTP.IDENTITY_CODING : "deflate"; HttpPost httpPost = new HttpPost(str); httpPost.addHeader(HTTP.CONTENT_TYPE, AbstractSpiCall.ACCEPT_JSON_VALUE); httpPost.addHeader(HTTP.CONTENT_ENCODING, str3); httpPost.addHeader(HTTP.USER_AGENT, System.getProperty("http.agent")); if (this.applicationToken == null) { this.log.error("Cannot create POST without an Application Token."); return null; }//from w ww.ja v a 2 s . c om httpPost.addHeader(APPLICATION_TOKEN_HEADER, this.applicationToken); if (this.serverTimestamp != 0) { httpPost.addHeader(CONNECT_TIME_HEADER, Long.valueOf(this.serverTimestamp).toString()); } if ("deflate".equals(str3)) { httpPost.setEntity(new ByteArrayEntity(deflate(str2))); } else { try { httpPost.setEntity(new StringEntity(str2, "utf-8")); } catch (Throwable e) { this.log.error("UTF-8 is unsupported"); throw new IllegalArgumentException(e); } } return httpPost; }