List of usage examples for org.apache.http.params CoreProtocolPNames USER_AGENT
String USER_AGENT
To view the source code for org.apache.http.params CoreProtocolPNames USER_AGENT.
Click Source Link
From source file:com.adavr.http.Client.java
public void setUserAgent(String ua) { httpClient.getParams().setParameter(CoreProtocolPNames.USER_AGENT, ua); }
From source file:org.s1.testing.httpclient.TestHttpClient.java
/** * * @param u/*from w ww . j av a 2 s. com*/ * @param data * @param headers * @return */ public HttpResponseBean postForm(String u, Map<String, Object> data, Map<String, String> headers) { if (headers == null) headers = new HashMap<String, String>(); u = getURL(u, null); HttpPost post = new HttpPost(u); try { headers.put("Content-Type", "application/x-www-form-urlencoded"); for (String h : headers.keySet()) { post.setHeader(h, "" + headers.get(h)); } //HttpPost post = new HttpPost(LOGIN_URL); List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>(); if (data != null) { for (String h : data.keySet()) { params.add(new BasicNameValuePair(h, (String) data.get(h))); } } UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(params, Charset.forName("UTF-8")); post.setEntity(urlEncodedFormEntity); client.getParams().setParameter(CoreProtocolPNames.USER_AGENT, "Test Browser"); client.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); //client.getParams().setParameter(ClientPNames.COOKIE_POLICY, org.apache.http.client.params.CookiePolicy.BROWSER_COMPATIBILITY); HttpResponse resp = null; try { resp = client.execute(host, post, context); } catch (IOException e) { throw new RuntimeException(e.getMessage(), e); } Map<String, String> rh = new HashMap<String, String>(); for (Header h : resp.getAllHeaders()) { rh.put(h.getName(), h.getValue()); } try { HttpResponseBean r = new HttpResponseBean(resp.getStatusLine().getStatusCode(), rh, EntityUtils.toByteArray(resp.getEntity())); printIfError(u, r); return r; } catch (IOException e) { throw new RuntimeException(e.getMessage(), e); } } finally { post.releaseConnection(); } }
From source file:org.sonatype.nexus.client.rest.jersey.NexusClientFactoryImpl.java
protected ApacheHttpClient4 doCreateHttpClientFor(final ConnectionInfo connectionInfo, final XStream xstream) { final ApacheHttpClient4Config config = new DefaultApacheHttpClient4Config(); config.getSingletons().add(new XStreamXmlProvider(xstream, APPLICATION_XML_UTF8_TYPE)); // set _real_ URL for baseUrl, and not a redirection (typically http instead of https) config.getProperties().put(PROPERTY_FOLLOW_REDIRECTS, Boolean.FALSE); applyAuthenticationIfAny(connectionInfo, config); applyProxyIfAny(connectionInfo, config); // obey JSSE defined system properties config.getProperties().put(ApacheHttpClient4Config.PROPERTY_CONNECTION_MANAGER, new PoolingClientConnectionManager(SchemeRegistryFactory.createSystemDefault())); final ApacheHttpClient4 client = ApacheHttpClient4.create(config); // set UA//from www.j a v a 2 s . c om client.getClientHandler().getHttpClient().getParams().setParameter(CoreProtocolPNames.USER_AGENT, "Nexus-Client/" + discoverClientVersion()); // "tweak" HTTPS scheme as requested final TrustStrategy trustStrategy; switch (connectionInfo.getSslCertificateValidation()) { case NONE: trustStrategy = new TrustStrategy() { @Override public boolean isTrusted(final X509Certificate[] chain, final String authType) throws CertificateException { return true; } }; break; case LAX: trustStrategy = new TrustSelfSignedStrategy(); break; default: trustStrategy = null; } final X509HostnameVerifier hostnameVerifier; switch (connectionInfo.getSslCertificateHostnameValidation()) { case NONE: hostnameVerifier = new AllowAllHostnameVerifier(); break; case STRICT: hostnameVerifier = new StrictHostnameVerifier(); break; default: hostnameVerifier = new BrowserCompatHostnameVerifier(); } try { final SSLSocketFactory ssf = new SSLSocketFactory(trustStrategy, hostnameVerifier); final Scheme tweakedHttpsScheme = new Scheme("https", 443, ssf); client.getClientHandler().getHttpClient().getConnectionManager().getSchemeRegistry() .register(tweakedHttpsScheme); } catch (Exception e) { Throwables.propagate(e); } // NXCM-4547 JERSEY-1293 Enforce proxy setting on httpclient enforceProxyUri(config, client); if (LOG.isDebugEnabled()) { client.addFilter(new LoggingFilter()); } client.addFilter(new RequestFilters()); return client; }
From source file:com.norconex.collector.http.client.impl.DefaultHttpClientInitializer.java
@Override public void initializeHTTPClient(DefaultHttpClient httpClient) { // Time out after 30 seconds. //TODO Make configurable. httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, CONNECTION_TIMEOUT); // Add support for FTP websites (FTP served by HTTP server). Scheme ftp = new Scheme("ftp", FTP_PORT, new PlainSocketFactory()); httpClient.getConnectionManager().getSchemeRegistry().register(ftp); //TODO make charset configurable instead since UTF-8 is not right // charset for URL specifications. It is used here to overcome // so invalid redirect errors, where the redirect target URL is not // URL-Encoded and has non-ascii values, and fails // (e.g. like ja.wikipedia.org). // Can consider a custom RedirectStrategy too if need be. httpClient.getParams().setParameter(CoreProtocolPNames.HTTP_ELEMENT_CHARSET, "UTF-8"); if (StringUtils.isNotBlank(proxyHost)) { httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, new HttpHost(proxyHost, proxyPort)); if (StringUtils.isNotBlank(proxyUsername)) { httpClient.getCredentialsProvider().setCredentials(new AuthScope(proxyHost, proxyPort), new UsernamePasswordCredentials(proxyUsername, proxyPassword)); }//from ww w . j av a2s . c om } if (!cookiesDisabled) { httpClient.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY); } if (AUTH_METHOD_FORM.equalsIgnoreCase(authMethod)) { authenticateUsingForm(httpClient); } else if (AUTH_METHOD_BASIC.equalsIgnoreCase(authMethod)) { setupBasicDigestAuth(httpClient); } else if (AUTH_METHOD_DIGEST.equalsIgnoreCase(authMethod)) { setupBasicDigestAuth(httpClient); } if (userAgent != null) { httpClient.getParams().setParameter(CoreProtocolPNames.USER_AGENT, userAgent); } }
From source file:dk.kk.ibikecphlib.util.HttpUtils.java
public static JsonNode putToServer(String urlString, JSONObject objectToPost) { JsonNode ret = null;//from www . jav a 2s . co m LOG.d("PUT api request, url = " + urlString); HttpParams myParams = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(myParams, CONNECTON_TIMEOUT); HttpConnectionParams.setSoTimeout(myParams, CONNECTON_TIMEOUT); HttpClient httpclient = new DefaultHttpClient(myParams); httpclient.getParams().setParameter(CoreProtocolPNames.USER_AGENT, Config.USER_AGENT); HttpPut httput = null; URL url = null; try { url = new URL(urlString); httput = new HttpPut(url.toString()); httput.setHeader("Content-type", "application/json"); httput.setHeader("Accept", ACCEPT); httput.setHeader("LANGUAGE_CODE", IBikeApplication.getLanguageString()); StringEntity se = new StringEntity(objectToPost.toString(), HTTP.UTF_8); se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json")); httput.setEntity(se); HttpResponse response = httpclient.execute(httput); String serverResponse = EntityUtils.toString(response.getEntity()); LOG.d("API response = " + serverResponse); ret = Util.stringToJsonNode(serverResponse); } catch (Exception e) { if (e != null && e.getLocalizedMessage() != null) { LOG.e(e.getLocalizedMessage()); } } return ret; }
From source file:org.brunocvcunha.taskerbox.core.http.TaskerboxHttpBox.java
/** * Build a new HTTP Client for the given parameters * * @param params//from w ww . j a va2 s . co m * @return */ public DefaultHttpClient buildNewHttpClient(HttpParams params) { PoolingClientConnectionManager cxMgr = new PoolingClientConnectionManager( SchemeRegistryFactory.createDefault()); cxMgr.setMaxTotal(100); cxMgr.setDefaultMaxPerRoute(20); DefaultHttpClient httpClient = new DefaultHttpClient(cxMgr, params); httpClient.getParams().setParameter(CoreProtocolPNames.USER_AGENT, "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.111 Safari/537.36"); // httpClient.getParams().setParameter(ClientPNames.COOKIE_POLICY, // CookiePolicy.BROWSER_COMPATIBILITY); if (this.useNtlm) { httpClient.getAuthSchemes().register("NTLM", new NTLMSchemeFactory()); httpClient.getAuthSchemes().register("BASIC", new BasicSchemeFactory()); httpClient.getAuthSchemes().register("DIGEST", new DigestSchemeFactory()); httpClient.getAuthSchemes().register("SPNEGO", new SPNegoSchemeFactory()); httpClient.getAuthSchemes().register("KERBEROS", new KerberosSchemeFactory()); } try { SSLContext sc = SSLContext.getInstance("SSL"); sc.init(null, getTrustingManager(), new java.security.SecureRandom()); SSLSocketFactory socketFactory = new SSLSocketFactory(sc); Scheme sch = new Scheme("https", 443, socketFactory); httpClient.getConnectionManager().getSchemeRegistry().register(sch); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (KeyManagementException e) { e.printStackTrace(); } if (this.useProxy) { if (this.proxySocks) { log.info("Using proxy socks " + this.socksHost + ":" + this.socksPort); System.setProperty("socksProxyHost", this.socksHost); System.setProperty("socksProxyPort", String.valueOf(this.socksPort)); } else { HttpHost proxy = new HttpHost(this.proxyHost, this.proxyPort); httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy); if (this.authProxy) { List<String> authPreferences = new ArrayList<>(); if (this.ntlmProxy) { NTCredentials creds = new NTCredentials(this.proxyUser, this.proxyPassword, this.proxyWorkstation, this.proxyDomain); httpClient.getCredentialsProvider() .setCredentials(new AuthScope(this.proxyHost, this.proxyPort), creds); // httpClient.getCredentialsProvider().setCredentials( // AuthScope.ANY, creds); authPreferences.add(AuthPolicy.NTLM); } else { UsernamePasswordCredentials creds = new UsernamePasswordCredentials(this.proxyUser, this.proxyPassword); httpClient.getCredentialsProvider().setCredentials(AuthScope.ANY, creds); authPreferences.add(AuthPolicy.BASIC); } httpClient.getParams().setParameter(AuthPNames.TARGET_AUTH_PREF, authPreferences); } } } return httpClient; }
From source file:com.gitblit.plugin.slack.Slacker.java
/** * Send a payload message./*from w w w.jav a 2 s . co m*/ * * @param payload * @throws IOException */ public void send(Payload payload) throws IOException { String slackUrl = getURL(); payload.setUnfurlLinks(true); if (StringUtils.isEmpty(payload.getUsername())) { payload.setUsername(Constants.NAME); } String defaultChannel = runtimeManager.getSettings().getString(Plugin.SETTING_DEFAULT_CHANNEL, null); if (!StringUtils.isEmpty(defaultChannel) && StringUtils.isEmpty(payload.getChannel())) { // specify the default channel if (defaultChannel.charAt(0) != '#' && defaultChannel.charAt(0) != '@') { defaultChannel = "#" + defaultChannel; } // channels must be lowercase payload.setChannel(defaultChannel.toLowerCase()); } String defaultEmoji = runtimeManager.getSettings().getString(Plugin.SETTING_DEFAULT_EMOJI, null); if (!StringUtils.isEmpty(defaultEmoji)) { if (StringUtils.isEmpty(payload.getIconEmoji()) && StringUtils.isEmpty(payload.getIconUrl())) { // specify the default emoji payload.setIconEmoji(defaultEmoji); } } Gson gson = new GsonBuilder().create(); String json = gson.toJson(payload); log.debug(json); HttpClient client = new DefaultHttpClient(); HttpPost post = new HttpPost(slackUrl); post.getParams().setParameter(CoreProtocolPNames.USER_AGENT, Constants.NAME + "/" + Constants.getVersion()); post.getParams().setParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET, "UTF-8"); client.getParams().setParameter(AllClientPNames.CONNECTION_TIMEOUT, 5000); client.getParams().setParameter(AllClientPNames.SO_TIMEOUT, 5000); List<NameValuePair> nvps = new ArrayList<NameValuePair>(1); nvps.add(new BasicNameValuePair("payload", json)); post.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8")); HttpResponse response = client.execute(post); int rc = response.getStatusLine().getStatusCode(); if (HttpStatus.SC_OK == rc) { // replace this with post.closeConnection() after JGit updates to HttpClient 4.2 post.abort(); } else { String result = null; InputStream is = response.getEntity().getContent(); try { byte[] buffer = new byte[8192]; ByteArrayOutputStream os = new ByteArrayOutputStream(); int len = 0; while ((len = is.read(buffer)) > -1) { os.write(buffer, 0, len); } result = os.toString("UTF-8"); } finally { if (is != null) { is.close(); } } log.error("Slack plugin sent:"); log.error(json); log.error("Slack returned:"); log.error(result); throw new IOException(String.format("Slack Error (%s): %s", rc, result)); } }
From source file:cn.mdict.utils.IOUtil.java
public static boolean httpGetFile(String url, OutputStream os, StatusReport statusReport) { try {/*from w ww. j a v a2 s . c o m*/ HttpClient client = new DefaultHttpClient(); client.getParams().setParameter(CoreProtocolPNames.USER_AGENT, HttpUserAgent); HttpGet get = new HttpGet(url); if (statusReport != null) statusReport.onStart(); HttpResponse response = client.execute(get); if (response.getStatusLine() != null && response.getStatusLine().getStatusCode() != 200) { get.abort(); return false; } HttpEntity entity = response.getEntity(); long length = entity.getContentLength(); if (statusReport != null) statusReport.onGetTotal(length); boolean result = streamDuplicate(entity.getContent(), os, statusReport); return result; } catch (Exception e) { if (statusReport != null) statusReport.onError(e); else e.printStackTrace(); } return false; }
From source file:org.centum.android.communicators.StudyStackCommunicator.java
private String getJSONData(URI uri) throws IOException { HttpClient client = new DefaultHttpClient(); client.getParams().setParameter(CoreProtocolPNames.USER_AGENT, "android"); HttpGet request = new HttpGet(); request.setHeader("Content-Type", "text/plain; charset=utf-8"); request.setURI(uri);/*from ww w .j a v a2s.com*/ HttpResponse response = client.execute(request); BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); StringBuffer stringBuffer = new StringBuffer(""); String line; String NL = System.getProperty("line.separator"); while ((line = in.readLine()) != null) { stringBuffer.append(line + NL); } in.close(); return stringBuffer.toString(); }
From source file:com.ichi2.libanki.sync.BasicHttpSyncer.java
public HttpResponse req(String method, InputStream fobj, int comp, boolean hkey, JSONObject registerData, Connection.CancelCallback cancelCallback) { File tmpFileBuffer = null;/*from ww w . j a v a2s .co m*/ try { String bdry = "--" + BOUNDARY; StringWriter buf = new StringWriter(); // compression flag and session key as post vars buf.write(bdry + "\r\n"); buf.write("Content-Disposition: form-data; name=\"c\"\r\n\r\n" + (comp != 0 ? 1 : 0) + "\r\n"); if (hkey) { buf.write(bdry + "\r\n"); buf.write("Content-Disposition: form-data; name=\"k\"\r\n\r\n" + mHKey + "\r\n"); } tmpFileBuffer = File.createTempFile("syncer", ".tmp", new File(AnkiDroidApp.getCacheStorageDirectory())); FileOutputStream fos = new FileOutputStream(tmpFileBuffer); BufferedOutputStream bos = new BufferedOutputStream(fos); GZIPOutputStream tgt; // payload as raw data or json if (fobj != null) { // header buf.write(bdry + "\r\n"); buf.write( "Content-Disposition: form-data; name=\"data\"; filename=\"data\"\r\nContent-Type: application/octet-stream\r\n\r\n"); buf.close(); bos.write(buf.toString().getBytes("UTF-8")); // write file into buffer, optionally compressing int len; BufferedInputStream bfobj = new BufferedInputStream(fobj); byte[] chunk = new byte[65536]; if (comp != 0) { tgt = new GZIPOutputStream(bos); while ((len = bfobj.read(chunk)) >= 0) { tgt.write(chunk, 0, len); } tgt.close(); bos = new BufferedOutputStream(new FileOutputStream(tmpFileBuffer, true)); } else { while ((len = bfobj.read(chunk)) >= 0) { bos.write(chunk, 0, len); } } bos.write(("\r\n" + bdry + "--\r\n").getBytes("UTF-8")); } else { buf.close(); bos.write(buf.toString().getBytes("UTF-8")); } bos.flush(); bos.close(); // connection headers String url = Collection.SYNC_URL; if (method.equals("register")) { url = url + "account/signup" + "?username=" + registerData.getString("u") + "&password=" + registerData.getString("p"); } else if (method.startsWith("upgrade")) { url = url + method; } else { url = url + "sync/" + method; } HttpPost httpPost = new HttpPost(url); HttpEntity entity = new ProgressByteEntity(tmpFileBuffer); // body httpPost.setEntity(entity); httpPost.setHeader("Content-type", "multipart/form-data; boundary=" + BOUNDARY); // HttpParams HttpParams params = new BasicHttpParams(); params.setParameter(ConnManagerPNames.MAX_TOTAL_CONNECTIONS, 30); params.setParameter(ConnManagerPNames.MAX_CONNECTIONS_PER_ROUTE, new ConnPerRouteBean(30)); params.setParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, false); params.setParameter(CoreProtocolPNames.USER_AGENT, "AnkiDroid-" + AnkiDroidApp.getPkgVersion()); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); HttpConnectionParams.setSoTimeout(params, Connection.CONN_TIMEOUT); // Registry SchemeRegistry registry = new SchemeRegistry(); registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); registry.register(new Scheme("https", new EasySSLSocketFactory(), 443)); ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(params, registry); if (cancelCallback != null) { cancelCallback.setConnectionManager(cm); } try { HttpClient httpClient = new DefaultHttpClient(cm, params); return httpClient.execute(httpPost); } catch (SSLException e) { Log.e(AnkiDroidApp.TAG, "SSLException while building HttpClient", e); return null; } } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } catch (IOException e) { Log.e(AnkiDroidApp.TAG, "BasicHttpSyncer.sync: IOException", e); return null; } catch (JSONException e) { throw new RuntimeException(e); } finally { if (tmpFileBuffer != null && tmpFileBuffer.exists()) { tmpFileBuffer.delete(); } } }