Example usage for org.apache.http.params CoreProtocolPNames USER_AGENT

List of usage examples for org.apache.http.params CoreProtocolPNames USER_AGENT

Introduction

In this page you can find the example usage for org.apache.http.params CoreProtocolPNames USER_AGENT.

Prototype

String USER_AGENT

To view the source code for org.apache.http.params CoreProtocolPNames USER_AGENT.

Click Source Link

Usage

From source file:anhttpclient.impl.DefaultWebBrowser.java

private HttpParams getBasicHttpParams() {
    HttpParams params = new BasicHttpParams();
    params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
    params.setParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET, HTTP.UTF_8);
    params.setParameter(CoreProtocolPNames.USER_AGENT, WebBrowserConstants.DEFAULT_USER_AGENT);
    params.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, connectionTimeout);
    params.setParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, false);
    params.setParameter(ClientPNames.CONNECTION_MANAGER_FACTORY_CLASS_NAME, clientConnectionFactoryClassName);

    /*Custom parameter to be used in implementation of {@link ClientConnectionManagerFactory}*/
    params.setParameter(ClientConnectionManagerFactoryImpl.THREAD_SAFE_CONNECTION_MANAGER, this.threadSafe);

    return params;
}

From source file:com.seajas.search.contender.service.ContenderService.java

/**
 * Retrieve content via the retrieval HTTP client and the given handler.
 *
 * @param handler//from w w w .  ja va  2 s.  c om
 * @param userAgent
 * @param resultHeaders
 * @param allowLocal
 * @return SizeRestrictedHttpResponse
 */
public SizeRestrictedHttpResponse retrieveContent(final SizeRestrictedResponseHandler handler,
        final String userAgent, final Map<String, String> resultHeaders, final Boolean allowLocal) {
    try {
        if (!handler.getUri().getScheme().equalsIgnoreCase("file")) {
            HttpGet method = new HttpGet(handler.getUri());

            if (resultHeaders != null)
                for (Map.Entry<String, String> resultHeader : resultHeaders.entrySet())
                    method.setHeader(new BasicHeader(resultHeader.getKey(), resultHeader.getValue()));
            if (userAgent != null)
                method.setHeader(CoreProtocolPNames.USER_AGENT, userAgent);

            return httpClient.execute(method, handler);
        } else {
            if (allowLocal) {
                InputStream inputStream = new FileInputStream(handler.getUri().getPath());

                return new SizeRestrictedHttpResponse(null, IOUtils.readBytesFromStream(inputStream));
            } else {
                logger.error("Local resource requested, but local retrieval has not explicitly been allowed");

                return null;
            }
        }
    } catch (IOException e) {
        logger.error("Could not retrieve resource " + handler.getUri(), e);

        return null;
    }
}

From source file:org.centum.android.communicators.QuizletCommunicator.java

private JSONObject getJSONObject(URI uri) throws IOException, JSONException {
    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);/* w  ww.  java  2 s .c  o  m*/
    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 new JSONObject(stringBuffer.toString());
}

From source file:com.hichinaschool.flashcards.libanki.sync.BasicHttpSyncer.java

public HttpResponse req(String method, InputStream fobj, int comp, boolean hkey, JSONObject registerData,
        Connection.CancelCallback cancelCallback) {
    File tmpFileBuffer = null;/* ww w.j  a  v a  2s  . com*/
    try {
        String bdry = "--" + BOUNDARY;
        StringWriter buf = new StringWriter();
        HashMap<String, Object> vars = new HashMap<String, Object>();
        // compression flag and session key as post vars
        vars.put("c", comp != 0 ? 1 : 0);
        if (hkey) {
            vars.put("k", mHKey);
            vars.put("s", mSKey);
        }
        for (String key : vars.keySet()) {
            buf.write(bdry + "\r\n");
            buf.write(String.format(Locale.US, "Content-Disposition: form-data; name=\"%s\"\r\n\r\n%s\r\n", key,
                    vars.get(key)));
        }
        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.getPkgVersionName());
        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();
        }
    }
}

From source file:com.spoiledmilk.ibikecph.util.HttpUtils.java

public static JsonNode deleteFromServer(String urlString, JSONObject objectToPost) {
    JsonNode ret = null;/*from  w w w  .ja va 2s. c o  m*/
    LOG.d("DELETE 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);
    HTTPDeleteWithBody httpdelete = null;
    URL url = null;
    try {
        url = new URL(urlString);
        httpdelete = new HTTPDeleteWithBody(url.toString());
        httpdelete.setHeader("Content-type", "application/json");
        httpdelete.setHeader("Accept", ACCEPT);
        httpdelete.setHeader("LANGUAGE_CODE", IbikeApplication.getLanguageString());
        StringEntity se = new StringEntity(objectToPost.toString(), HTTP.UTF_8);
        se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
        httpdelete.setEntity(se);
        HttpResponse response = httpclient.execute(httpdelete);
        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:dk.kk.ibikecphlib.util.HttpUtils.java

public static JsonNode deleteFromServer(String urlString, JSONObject objectToPost) {
    JsonNode ret = null;/*from   w  w  w  . j  a  v a 2  s  .  com*/
    LOG.d("DELETE 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);
    HTTPDeleteWithBody httpdelete = null;
    URL url = null;
    try {
        url = new URL(urlString);
        httpdelete = new HTTPDeleteWithBody(url.toString());
        httpdelete.setHeader("Content-type", "application/json");
        httpdelete.setHeader("Accept", ACCEPT);
        httpdelete.setHeader("LANGUAGE_CODE", IBikeApplication.getLanguageString());
        StringEntity se = new StringEntity(objectToPost.toString(), HTTP.UTF_8);
        se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
        httpdelete.setEntity(se);
        HttpResponse response = httpclient.execute(httpdelete);
        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.s1.testing.httpclient.TestHttpClient.java

/**
 *
 * @param u//  w w w.j  ava2  s  . c o m
 * @param data
 * @param headers
 * @return
 */
public HttpResponseBean post(String u, InputStream data, Map<String, String> headers) {
    if (headers == null)
        headers = new HashMap<String, String>();

    u = getURL(u, null);
    HttpPost post = new HttpPost(u);
    try {
        for (String h : headers.keySet()) {
            post.setHeader(h, headers.get(h));
        }
        HttpEntity request = new InputStreamEntity(data, -1);
        post.setEntity(request);
        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();
    }
}