Example usage for org.apache.http.params HttpParams setParameter

List of usage examples for org.apache.http.params HttpParams setParameter

Introduction

In this page you can find the example usage for org.apache.http.params HttpParams setParameter.

Prototype

HttpParams setParameter(String str, Object obj);

Source Link

Usage

From source file:org.redhat.jboss.httppacemaker.ProxyServlet.java

@Override
public void init(ServletConfig servletConfig) throws ServletException {
    super.init(servletConfig);

    String doLogStr = servletConfig.getInitParameter(P_LOG);
    if (doLogStr != null) {
        this.doLog = Boolean.parseBoolean(doLogStr);
    }/*from  w ww.ja  v  a  2s .c  o  m*/

    targetUri = buildURI(retrieveParameterFromContext(servletConfig, P_TARGET_URI));

    HttpParams hcParams = new BasicHttpParams();
    String hcParamName = ClientPNames.HANDLE_REDIRECTS;
    hcParams.setParameter(hcParamName, ReflectUtils
            .invokeValueOfOnString(getServletConfig().getInitParameter(hcParamName), Boolean.class));
    proxyClient = createHttpClient(hcParams);
}

From source file:org.cm.podd.report.service.DataSubmitService.java

private boolean submitReport(Report report) throws URISyntaxException, IOException, JSONException {

    HttpParams params = new BasicHttpParams();
    params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
    HttpClient client = new DefaultHttpClient(params);
    boolean success = false;

    try {//from  ww w.j av a2  s  .c  o m

        String serverUrl = settings.getString("serverUrl", BuildConfig.SERVER_URL);

        URI http = new URI(serverUrl + "/reports/");
        Log.i(TAG, "submit report url=" + http.toURL());

        HttpPost post = new HttpPost(http);
        post.setHeader("Content-type", "application/json");
        post.setHeader("Authorization", "Token " + sharedPrefUtil.getAccessToken());

        SimpleDateFormat sdfDateTime = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
        SimpleDateFormat sdfDate = new SimpleDateFormat("yyyy-MM-dd");

        JSONObject data = new JSONObject();
        data.put("reportId", report.getId());
        data.put("guid", report.getGuid());
        data.put("reportTypeId", report.getType());
        if (report.getFollowFlag() == Report.TRUE) {
            data.put("date", sdfDateTime.format(report.getFollowDate()));
            data.put("followFlag", Report.TRUE);
            data.put("parentGuid", report.getParentGuid());
        } else {
            data.put("date", sdfDateTime.format(report.getDate()));
        }
        Date startDate = report.getStartDate();
        if (startDate == null) {
            startDate = new Date();
        }
        data.put("incidentDate", sdfDate.format(startDate));
        if (report.getRegionId() != 0) {
            data.put("administrationAreaId", report.getRegionId());
        }
        if (report.getLatitude() != 0.00 && report.getLongitude() != 0.00) {
            JSONObject loc = new JSONObject();
            loc.put("latitude", report.getLatitude());
            loc.put("longitude", report.getLongitude());

            data.put("reportLocation", loc);
        }

        data.put("remark", report.getRemark());
        data.put("negative", report.getNegative() == 1);

        JSONObject formObj = report.getNegative() == 1 ? report.getSubmitJSONFormData() : new JSONObject();
        formObj.put("programVersion", BuildConfig.VERSION_CODE);
        formObj.put("reportTypeVersion", report.getReportTypeVersion());
        data.put("formData", formObj);

        if (report.isTestReport()) {
            data.put("testFlag", true);
        } else {
            data.put("testFlag", false);
        }

        post.setEntity(new StringEntity(data.toString(), HTTP.UTF_8));
        Log.d(TAG, "request with " + EntityUtils.toString(post.getEntity()));

        HttpResponse response;
        response = client.execute(post);
        HttpEntity entity = response.getEntity();

        // Detect server complaints
        int statusCode = response.getStatusLine().getStatusCode();
        Log.d(TAG, "status code=" + statusCode);

        if (statusCode == HttpURLConnection.HTTP_INTERNAL_ERROR) {
            Log.e(TAG, "error " + EntityUtils.toString(response.getEntity()));
        }
        success = statusCode == 201;
        entity.consumeContent();

    } finally {
        client.getConnectionManager().shutdown();
    }
    return success;
}

From source file:org.apache.abdera2.common.protocol.BasicClient.java

protected void initDefaultParameters(HttpParams params) {
    params.setParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, Boolean.TRUE);
    params.setParameter(ClientPNames.MAX_REDIRECTS, DEFAULT_MAX_REDIRECTS);
    params.setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY);
}

From source file:org.hyperic.hq.plugin.netservices.HTTPCollector.java

private HttpResponse getRedirect(String url, String args) throws ClientProtocolException, IOException {
    HttpConfig config = new HttpConfig(getTimeoutMillis(), getTimeoutMillis(), proxyHost.get(),
            proxyPort.get());/*from w w w.j a  v  a2 s .  com*/
    AgentKeystoreConfig keystoreConfig = new AgentKeystoreConfig();
    HQHttpClient client = new HQHttpClient(keystoreConfig, config, keystoreConfig.isAcceptUnverifiedCert());
    HttpParams params = client.getParams();
    params.setParameter(CoreProtocolPNames.USER_AGENT, useragent.get());
    if (this.hosthdr != null) {
        params.setParameter(ClientPNames.VIRTUAL_HOST, this.hosthdr);
    }
    HttpRequestBase request;
    request = new HttpGet(url);
    addParams(request, getArgs(args));
    addCredentials(request, client);
    return client.execute(request);
}

From source file:com.ibuildapp.romanblack.TableReservationPlugin.TableReservationEMailSignUpActivity.java

/**
 * Validate input data and signs up new user on iBuildApp.
 *///  www  .j  a  v a 2 s. c  om
private void registration() {
    if (signUpActive) {
        handler.sendEmptyMessage(SHOW_PROGRESS_DIALOG);

        new Thread(new Runnable() {
            public void run() {

                HttpParams params = new BasicHttpParams();
                params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
                HttpClient httpClient = new DefaultHttpClient(params);

                try {
                    HttpPost httpPost = new HttpPost(TableReservationHTTP.SIGNUP_URL);

                    String firstNameString = firstNameEditText.getText().toString();
                    String lastNameString = lastNameEditText.getText().toString();
                    String emailString = emailEditText.getText().toString();
                    String passwordString = passwordEditText.getText().toString();
                    String rePasswordString = rePasswordEditText.getText().toString();

                    MultipartEntity multipartEntity = new MultipartEntity();
                    multipartEntity.addPart("firstname",
                            new StringBody(firstNameString, Charset.forName("UTF-8")));
                    multipartEntity.addPart("lastname",
                            new StringBody(lastNameString, Charset.forName("UTF-8")));
                    multipartEntity.addPart("email", new StringBody(emailString, Charset.forName("UTF-8")));
                    multipartEntity.addPart("password",
                            new StringBody(passwordString, Charset.forName("UTF-8")));
                    multipartEntity.addPart("password_confirm",
                            new StringBody(rePasswordString, Charset.forName("UTF-8")));

                    // add security part
                    multipartEntity.addPart("app_id", new StringBody(Statics.appId, Charset.forName("UTF-8")));
                    multipartEntity.addPart("token",
                            new StringBody(Statics.appToken, Charset.forName("UTF-8")));

                    httpPost.setEntity(multipartEntity);

                    String resp = httpClient.execute(httpPost, new BasicResponseHandler());

                    fwUser = JSONParser.parseLoginRequestString(resp);

                    if (fwUser == null) {
                        handler.sendEmptyMessage(EMEIL_IN_USE);
                        handler.sendEmptyMessage(HIDE_PROGRESS_DIALOG);
                        return;
                    }

                    handler.sendEmptyMessage(HIDE_PROGRESS_DIALOG);

                    handler.sendEmptyMessage(CLOSE_ACTIVITY_OK);

                } catch (Exception e) {
                    handler.sendEmptyMessage(CLOSE_ACTIVITY_BAD);
                }

            }
        }).start();
    } else {
        if (firstNameEditText.getText().toString().length() == 0
                || lastNameEditText.getText().toString().length() == 0
                || emailEditText.getText().toString().length() == 0
                || passwordEditText.getText().toString().length() == 0
                || rePasswordEditText.getText().toString().length() == 0) {
            Toast.makeText(this, R.string.alert_registration_fillin_fields, Toast.LENGTH_LONG).show();
            return;
        }

        if (firstNameEditText.getText().toString().equals(lastNameEditText.getText().toString())) {
            Toast.makeText(this, R.string.alert_registration_spam, Toast.LENGTH_LONG).show();
            return;
        }

        if (firstNameEditText.getText().toString().length() <= 2
                || lastNameEditText.getText().toString().length() <= 2) {
            Toast.makeText(this, R.string.alert_registration_two_symbols_name, Toast.LENGTH_LONG).show();
            return;
        }

        String regExpn = "^(([\\w-]+\\.)+[\\w-]+|([a-zA-Z]{1}|[\\w-]{2,}))@"
                + "((([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\\.([0-1]?" + "[0-9]{1,2}|25[0-5]|2[0-4][0-9])\\."
                + "([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\\.([0-1]?" + "[0-9]{1,2}|25[0-5]|2[0-4][0-9])){1}|"
                + "([a-zA-Z]+[\\w-]+\\.)+[a-zA-Z]{2,4})$";

        Pattern pattern = Pattern.compile(regExpn, Pattern.CASE_INSENSITIVE);
        Matcher matcher = pattern.matcher(emailEditText.getText().toString());

        if (matcher.matches()) {
        } else {
            Toast.makeText(this, R.string.alert_registration_correct_email, Toast.LENGTH_LONG).show();
            return;
        }

        if (passwordEditText.getText().toString().length() < 4) {
            Toast.makeText(this, R.string.alert_registration_two_symbols_password, Toast.LENGTH_LONG).show();
            return;
        }

        if (!passwordEditText.getText().toString().equals(rePasswordEditText.getText().toString())) {
            Toast.makeText(this, "Passwords don't match.", Toast.LENGTH_LONG).show();
            return;
        }
    }
}

From source file:com.yahala.ui.LoginActivitySmsView.java

public void sendSmsRequest() {
    Utilities.globalQueue.postRunnable(new Runnable() {
        @Override/* ww w . java 2s.  c o  m*/
        public void run() {

            try {
                HttpParams httpParams = new BasicHttpParams();

                httpParams.setParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET, HTTP.UTF_8);
                httpParams.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);

                SchemeRegistry registry = new SchemeRegistry();

                KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
                trustStore.load(null, null);
                SSLSocketFactory sf = new MySSLSocketFactory(trustStore);

                sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

                registry.register(new Scheme("http", new PlainSocketFactory(), 80));
                registry.register(new Scheme("https", sf, 443));
                ThreadSafeClientConnManager manager = new ThreadSafeClientConnManager(httpParams, registry);

                HttpClient httpClient = new DefaultHttpClient(manager, httpParams);

                // HttpGet httpget = new HttpGet("/nhttps://api.clickatell.com/http/sendmsg?user=***********&password=***********&api_id=***********&to=" + requestPhone + "&text=Your%20Yahala%20verification%20code:%20"+ phoneHash);
                HttpGet httpget = new HttpGet(
                        "https://rest.nexmo.com/sms/json?api_key=***********&api_secret=***********=NEXMO&to="
                                + requestPhone + "&text=Your%20Yahala%20verification%20code:%20" + phoneHash);

                if (!Utils.IsInDebugMode()) {
                    HttpResponse response = httpClient.execute(httpget);
                    if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
                        FileLog.e("yahala", "Sms sent" + response.getEntity().getContent());
                    } else {
                        FileLog.e("/nyahala",
                                "https://api.clickatell.com/http/sendmsg?user=***********&password=***********&api_id=***********&to="
                                        + requestPhone + "&text=Your%20Yahala%20verification%20code:%20"
                                        + phoneHash);
                    }

                } else {
                    Toast.makeText(getContext(), phoneHash, Toast.LENGTH_LONG);
                    FileLog.e("/nyahala",
                            "https://api.clickatell.com/http/sendmsg?user=***********&password=***********&api_id=***********&to="
                                    + requestPhone + "&text=Your%20Yahala%20verification%20code:%20"
                                    + phoneHash);

                }

            } catch (Exception e) {

                FileLog.e("yahala", e);

            }
        }
    });
}

From source file:org.apache.abdera2.common.protocol.BasicClient.java

protected HttpClient initClient(String useragent) {
    SchemeRegistry schemeRegistry = initSchemeRegistry();
    ClientConnectionManager cm = initConnectionManager(schemeRegistry);
    DefaultHttpClient client = new DefaultHttpClient(cm);
    HttpParams params = client.getParams();
    params.setParameter(CoreProtocolPNames.USER_AGENT, useragent);
    initDefaultParameters(params);/*from  ww  w .  j  a  v  a  2s  .  com*/
    return client;
}

From source file:com.nanocrawler.fetcher.PageFetcher.java

public PageFetcher(CrawlConfig config) {
    this.config = config;

    HttpParams params = new BasicHttpParams();
    HttpProtocolParamBean paramsBean = new HttpProtocolParamBean(params);
    paramsBean.setVersion(HttpVersion.HTTP_1_1);
    paramsBean.setContentCharset("UTF-8");
    paramsBean.setUseExpectContinue(false);
    params.setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY);
    params.setParameter(CoreProtocolPNames.USER_AGENT, config.getUserAgentString());
    params.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, config.getSocketTimeout());
    params.setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, config.getConnectionTimeout());
    params.setBooleanParameter("http.protocol.handle-redirects", false);

    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));
    if (config.isIncludeHttpsPages()) {
        schemeRegistry.register(new Scheme("https", 443, SSLSocketFactory.getSocketFactory()));
    }/*ww  w .  j  a v a2s .  c  o m*/

    connectionManager = new PoolingClientConnectionManager(schemeRegistry);
    connectionManager.setMaxTotal(config.getMaxTotalConnections());
    connectionManager.setDefaultMaxPerRoute(config.getMaxConnectionsPerHost());
    httpClient = new DefaultHttpClient(connectionManager, params);
}

From source file:free.yhc.netmbuddy.model.NetLoader.java

private HttpClient newHttpClient(String proxyAddr) {
    if (isValidProxyAddr(proxyAddr)) {
        // TODO// w  w w .  j  av  a2s . c o  m
        // Not supported yet.
        eAssert(false);
        return null;
    }
    HttpClient hc = new DefaultHttpClient();
    HttpParams params = hc.getParams();
    HttpConnectionParams.setConnectionTimeout(params, Policy.NETWORK_CONN_TIMEOUT);
    HttpConnectionParams.setSoTimeout(params, Policy.NETWORK_CONN_TIMEOUT);
    HttpProtocolParams.setUserAgent(hc.getParams(), Policy.HTTP_UASTRING);
    params.setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.RFC_2109);
    return hc;
}

From source file:com.ichi2.libanki.sync.HttpSyncer.java

public HttpResponse req(String method, InputStream fobj, int comp, JSONObject registerData,
        Connection.CancelCallback cancelCallback) throws UnknownHttpResponseException {
    File tmpFileBuffer = null;/*ww  w. ja  va 2  s. c om*/
    try {
        String bdry = "--" + BOUNDARY;
        StringWriter buf = new StringWriter();
        // post vars
        mPostVars.put("c", comp != 0 ? 1 : 0);
        for (String key : mPostVars.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,
                    mPostVars.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 = Consts.SYNC_BASE;
        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 = syncURL() + 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-" + VersionUtils.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);
            HttpResponse httpResponse = httpClient.execute(httpPost);
            // we assume badAuthRaises flag from Anki Desktop always False
            // so just throw new RuntimeException if response code not 200 or 403
            assertOk(httpResponse);
            return httpResponse;
        } catch (SSLException e) {
            Timber.e(e, "SSLException while building HttpClient");
            throw new RuntimeException("SSLException while building HttpClient");
        }
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException(e);
    } catch (IOException e) {
        Timber.e(e, "BasicHttpSyncer.sync: IOException");
        throw new RuntimeException(e);
    } catch (JSONException e) {
        throw new RuntimeException(e);
    } finally {
        if (tmpFileBuffer != null && tmpFileBuffer.exists()) {
            tmpFileBuffer.delete();
        }
    }
}