Example usage for org.apache.http.protocol HTTP UTF_8

List of usage examples for org.apache.http.protocol HTTP UTF_8

Introduction

In this page you can find the example usage for org.apache.http.protocol HTTP UTF_8.

Prototype

String UTF_8

To view the source code for org.apache.http.protocol HTTP UTF_8.

Click Source Link

Usage

From source file:cn.sharesdk.net.NetworkHelper.java

public static PostResult httpPost(String url, ArrayList<NameValuePair> pairs) {
    PostResult postResult = new PostResult();
    if (pairs == null || pairs.size() == 0) {
        postResult.setSuccess(false);//from  w w w .j  a v  a 2 s. co m
        postResult.setResponseMsg("post date of the request params is null !");
        return postResult;
    }

    try {
        HttpPost httppost = new HttpPost(url);
        httppost.addHeader("charset", HTTP.UTF_8);
        httppost.setHeader("Accept", "application/json,text/x-json,application/jsonrequest,text/json");

        HttpEntity entity = new UrlEncodedFormEntity(pairs, HTTP.UTF_8);
        httppost.setEntity(entity);

        HttpClient httpclient = new DefaultHttpClient();
        httpclient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 5000);
        httpclient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 5000);
        HttpResponse response = httpclient.execute(httppost);
        int status = response.getStatusLine().getStatusCode();

        String resString = EntityUtils.toString(response.getEntity());
        postResult = parse(status, resString);
    } catch (Exception e) {
        Ln.i("NetworkHelper", "=== post Ln ===", e);
    }

    return postResult;
}

From source file:me.xiaopan.android.gohttp.httpclient.MySSLSocketFactory.java

/**
 * Gets a DefaultHttpClient which trusts a set of certificates specified by the KeyStore
 *
 * @param keyStore//  w w  w .  j av  a2  s  .  c om
 * @return
 */
public static DefaultHttpClient getNewHttpClient(KeyStore keyStore) {
    try {
        SSLSocketFactory sf = new MySSLSocketFactory(keyStore);
        SchemeRegistry registry = new SchemeRegistry();
        registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
        registry.register(new Scheme("https", sf, 443));

        HttpParams params = new BasicHttpParams();
        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);

        ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);

        return new DefaultHttpClient(ccm, params);
    } catch (Exception e) {
        return new DefaultHttpClient();
    }
}

From source file:com.geekandroid.sdk.pay.utils.Util.java

private static HttpClient getNewHttpClient() {
    try {/*from  w w w  .j  av a 2s . c o m*/
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null, null);

        SSLSocketFactory sf = new SSLSocketFactoryEx(trustStore);
        sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

        HttpParams params = new BasicHttpParams();
        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);

        SchemeRegistry registry = new SchemeRegistry();
        registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
        registry.register(new Scheme("https", sf, 443));

        ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);

        return new DefaultHttpClient(ccm, params);
    } catch (Exception e) {
        return new DefaultHttpClient();
    }
}

From source file:com.bchalk.GVCallback.callback.GVCommunicator.java

public boolean login(String username, String password) {
    myError = "";
    if (username.trim().length() == 0 || password.trim().length() == 0) {
        myError = "No Google Voice login information saved!";
        return false;
    }//  w ww .j a  v a 2  s .  c  o m

    String token;

    myUsername = username;
    myPassword = password;

    myClient = new DefaultHttpClient();
    myClient.setRedirectHandler(new DefaultRedirectHandler());
    myClient.getParams().setBooleanParameter("http.protocol.expect-continue", false);

    List<NameValuePair> data = new ArrayList<NameValuePair>();
    data.add(new BasicNameValuePair("accountType", "GOOGLE"));
    data.add(new BasicNameValuePair("Email", username));
    data.add(new BasicNameValuePair("Passwd", password));
    data.add(new BasicNameValuePair("service", "grandcentral"));
    data.add(new BasicNameValuePair("source", "com-evancharlton-googlevoice-android-GV"));

    HttpPost post = new HttpPost("https://www.google.com/accounts/ClientLogin");
    myError = "";
    try {
        post.setEntity(new UrlEncodedFormEntity(data, HTTP.UTF_8));
        HttpResponse response = myClient.execute(post);
        BufferedReader is = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
        String line;
        while ((line = is.readLine()) != null) {
            if (line.startsWith("Auth")) {
                token = line.substring(5);
                storeToken(token);
                break;
            }
        }
        is.close();
        HttpGet get = new HttpGet("https://www.google.com/voice/m/i/voicemail?p=10000");
        response = myClient.execute(get);
        is = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
        Pattern rnrse = Pattern.compile("name=\"_rnr_se\"\\s*value=\"([^\"]+)\"");
        Pattern gvn = Pattern.compile("<b class=\"ms3\">([^<]+)</b>");
        Matcher m;
        boolean valid = false;
        boolean gvnvalid = false;
        while ((line = is.readLine()) != null) {
            if (line.indexOf("The username or password you entered is incorrect.") >= 0) {
                myError = "The username or password you entered is incorrect.";
                break;
            } else {
                if (line.indexOf("google.com/support/voice/bin/answer.py?answer=142423") >= 0) {
                    myError = "This Google Account does not have a Google Voice account.";
                    break;
                } else {
                    if (!gvnvalid) {
                        m = gvn.matcher(line);
                        if (m.find()) {
                            myGVNumber = normalizeNumber(m.group(1));
                            gvnvalid = true;
                        }
                    }

                    if (!valid) {
                        m = rnrse.matcher(line);
                        if (m.find()) {
                            myError = "";
                            myToken = m.group(1);
                            valid = true;
                        }
                    }

                    if (valid && gvnvalid)
                        break;
                }
            }
        }
        is.close();
        return valid;
    } catch (Exception e) {
        e.printStackTrace();
        myError = "Network error! Try cycling wi-fi (if enabled).";
    }

    if (myError.length() > 0)
        Log.e("GV Login Error", myError);
    return false;
}

From source file:com.fanfou.app.opensource.api.ApiClientImpl.java

@Override
public User blocksDelete(final String userId, final String mode) throws ApiException {
    // String url=String.format(URL_BLOCKS_DESTROY, userId);
    if (TextUtils.isEmpty(userId)) {
        throw new NullPointerException("blocksDelete() userId must not be empty or null.");
    }/*from  w  ww  . j  av a  2s.com*/
    String url;
    try {
        url = String.format(ApiConfig.URL_BLOCKS_DESTROY, URLEncoder.encode(userId, HTTP.UTF_8));
    } catch (final UnsupportedEncodingException e) {
        url = String.format(ApiConfig.URL_BLOCKS_DESTROY, userId);
    }

    final SimpleResponse response = doPostIdAction(url, null, null, mode);
    final int statusCode = response.statusCode;
    if (AppContext.DEBUG) {
        log("userUnblock()---statusCode=" + statusCode + " url=" + url);
    }

    // handlerResponseError(response);
    final User u = User.parse(response);
    if (u != null) {
        u.ownerId = AppContext.getUserId();
    }
    return u;
}

From source file:com.amalto.workbench.utils.ResourcesUtil.java

public static void postResourcesFromContentString(String content, String uri, String typeName)
        throws Exception {
    log.info(content);//from   w w w.j av a2s.  c om
    HttpPost httppost = new HttpPost(uri);
    List<BasicNameValuePair> nvps = new ArrayList<BasicNameValuePair>();
    nvps.add(new BasicNameValuePair("domainObjectName", typeName));//$NON-NLS-1$
    nvps.add(new BasicNameValuePair("domainObjectContent", content));//$NON-NLS-1$
    httppost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
    postContent(uri, httppost);
}

From source file:de.mprengemann.hwr.timetabel.data.Parser.java

protected Void doInBackground(Void... params) {
    this.exception = null;

    if (Utils.connectionChecker(context)) {
        try {/*from  ww w  . j av a2s  . c  om*/
            final String matrikelnr = preferences.getString(context.getString(R.string.prefs_matrikelNrKey),
                    "");

            DefaultHttpClient httpclient = new DefaultHttpClient();
            if (preferences.getBoolean(context.getString(R.string.prefs_proxyFlagKey), false)) {
                HttpHost proxy = new HttpHost(
                        preferences.getString(context.getString(R.string.prefs_proxyKey), "localhost"),
                        Integer.parseInt(
                                preferences.getString(context.getString(R.string.prefs_proxyPortKey), "8080")));
                httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
            }

            HttpGet httpget = new HttpGet(Utils.buildURL(context, preferences));

            HttpResponse response = httpclient.execute(httpget);
            HttpEntity entity = response.getEntity();

            if (entity != null) {
                entity.consumeContent();
            }

            List<Cookie> cookies = httpclient.getCookieStore().getCookies();

            HttpPost httpost = new HttpPost("http://ipool.ba-berlin.de/main.php?action=login");

            List<NameValuePair> nvps = new ArrayList<NameValuePair>();
            nvps.add(new BasicNameValuePair("FORM_LOGIN_NAME", "student"));
            nvps.add(new BasicNameValuePair("FORM_LOGIN_PASS", matrikelnr));
            nvps.add(new BasicNameValuePair("FORM_LOGIN_PAGE", "home"));
            nvps.add(new BasicNameValuePair("FORM_LOGIN_REDIRECTION", Utils.buildURL(context, preferences)));
            nvps.add(new BasicNameValuePair("FORM_ACCEPT", "1"));
            nvps.add(new BasicNameValuePair("LOGIN", "login"));

            httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));

            response = httpclient.execute(httpost);
            entity = response.getEntity();

            if (entity != null) {
                entity.consumeContent();
            }

            cookies = httpclient.getCookieStore().getCookies();

            final URL url;
            InputStream is = null;
            try {
                url = new URL(Utils.buildURL(context, preferences));
                URLConnection c = url.openConnection();

                try {
                    c.setRequestProperty("Cookie", cookies.get(0).getName() + "=" + cookies.get(0).getValue());
                    c.connect();
                    is = c.getInputStream();
                } catch (NullPointerException e) {
                    throw new ConnectionAuthentificationException(
                            context.getString(R.string.dialog_error_message_auth));
                } catch (IndexOutOfBoundsException e) {
                    throw new ConnectionAuthentificationException(
                            context.getString(R.string.dialog_error_message_auth));
                }

                if (is != null) {
                    try {
                        new IcsParser(is, new OnCalendarParsingListener() {

                            @Override
                            public void onNewItem(Component c) {
                                if (c.getName().equals(Component.VEVENT)) {
                                    PropertyList p = c.getProperties();

                                    Subjects s = new Subjects();
                                    s.setTitle(p.getProperty("SUMMARY").getValue());
                                    s.setShortTitle(s.getTitle().substring(s.getTitle().indexOf("-") + 1));
                                    s.setShow(true);

                                    SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd HHmmss");

                                    Events evt = new Events();
                                    try {
                                        evt.setStart(df
                                                .parse(p.getProperty("DTSTART").getValue().replace("T", " ")));
                                        evt.setEnd(
                                                df.parse(p.getProperty("DTEND").getValue().replace("T", " ")));
                                    } catch (ParseException e) {
                                        exception = new IPoolFormatException(
                                                context.getString(R.string.dialog_error_message_ipool));
                                        sendBugReport(e, url.toString());
                                    }

                                    evt.setRoom(p.getProperty("LOCATION").getValue());
                                    evt.setUid(p.getProperty("UID").getValue());

                                    String description = p.getProperty("DESCRIPTION").getValue();
                                    evt.setFullDescription(description);
                                    for (String desc : description.split("\\n")) {
                                        if (desc.startsWith("Dozent: ")) {
                                            evt.setLecturer(desc.replace("Dozent: ", ""));
                                            break;
                                        } else if (desc.startsWith("Art: ")) {
                                            evt.setType(desc.replace("Art: ", ""));
                                        }
                                    }
                                    try {
                                        if (listener != null) {
                                            listener.onNewItem(s, evt);
                                        }
                                    } catch (SQLiteConstraintException e) {
                                        exception = new StorageException(
                                                context.getString(R.string.dialog_error_message_storage));
                                        sendBugReport(e, url.toString(), s.toString(), evt.toString());
                                    }

                                }
                            }
                        });
                    } catch (ParserException e) {
                        exception = new UnknownTimetableException(
                                context.getString(R.string.dialog_error_message_auth));
                        sendNewTimetable(url);
                    } catch (IOException e) {
                        if (e instanceof HttpHostConnectException) {
                            exception = new ConnectionTimeoutException(
                                    context.getString(R.string.dialog_error_message_timeout));
                        } else {
                            exception = new ConnectionException(
                                    context.getString(R.string.dialog_error_message));
                        }
                    }
                } else {
                    throw new IOException();
                }
            } catch (ConnectionAuthentificationException e) {
                exception = e;
            } catch (IOException e) {
                if (e instanceof ConnectTimeoutException) {
                    exception = new ConnectionTimeoutException(
                            context.getString(R.string.dialog_error_message_timeout));
                } else if (e instanceof MalformedURLException) {
                    exception = new ConnectionException(context.getString(R.string.dialog_error_message));
                    sendBugReport(e);
                } else if (e instanceof HttpHostConnectException) {
                    exception = new ConnectionTimeoutException(
                            context.getString(R.string.dialog_error_message_timeout));
                } else {
                    exception = new ConnectionException(context.getString(R.string.dialog_error_message));
                    sendBugReport(e);
                }
            } finally {
                try {
                    if (is != null) {
                        is.close();
                    }
                } catch (IOException e) {
                    if (e instanceof ConnectTimeoutException) {
                        exception = new ConnectionTimeoutException(
                                context.getString(R.string.dialog_error_message_timeout));
                    } else {
                        exception = new ConnectionException(context.getString(R.string.dialog_error_message));
                        sendBugReport(e);
                    }
                }
            }

            httpclient.getConnectionManager().shutdown();
        } catch (Exception e) {
            if (e instanceof ConnectTimeoutException) {
                exception = new ConnectionTimeoutException(
                        context.getString(R.string.dialog_error_message_timeout));
            } else {
                exception = new ConnectionException(context.getString(R.string.dialog_error_message));
                sendBugReport(e);
            }

        }
    } else {
        exception = new ConnectionException(context.getString(R.string.dialog_error_message));
    }

    return null;
}

From source file:com.coodesoft.notee.NoteeNetworkReply.java

public boolean forgotPwd(String strUserName) {
    String strAction = "forgot_pwd";

    // http//from  ww  w.  j  a v a2  s . c om
    HttpPost httpPost = new HttpPost(m_strNoteeUrlBase + strAction);
    httpPost.addHeader("Connection", "Keep-Alive");

    // post parameter
    List<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new BasicNameValuePair("user_name", strUserName));
    // character set
    HttpEntity entity;
    try {
        entity = new UrlEncodedFormEntity(params, HTTP.UTF_8);
        httpPost.setEntity(entity);
    } catch (UnsupportedEncodingException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
        return false;
    }

    try {
        HttpResponse response = m_httpClient.execute(httpPost);

        if (parseResponse(response))
            return true;

    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return false;
}

From source file:orca.handlers.nlr.SherpaAPI.java

/**
 * Returns a vlan id that is available for use.
 * /*w w  w  .  j  a  v  a 2  s .  c  o  m*/
 * @param net
 * @param wg
 * @return vlan id
 */
public VlanIdDefinition get_available_vlan_id() throws Exception {
    String cmd = "?method=get_available_vlan_id";
    try {
        cmd += "&net=" + URLEncoder.encode(String.format("%d", net), HTTP.UTF_8);
        cmd += "&wg=" + URLEncoder.encode(String.format("%d", wg), HTTP.UTF_8);
    } catch (UnsupportedEncodingException e) {
    }

    Reader ret = sherpaSession.executePlanningCmd(cmd);

    Type myType = new TypeToken<SherpaAPIResponse<VlanIdDefinition>>() {
    }.getType();
    SherpaAPIResponse<VlanIdDefinition> resp = gson.fromJson(ret, myType);

    if (resp == null)
        throw new Exception("Unable to parse JSON output for command " + cmd);

    if ((resp.error == 0) || (resp.success == 1))
        return resp.results;
    else
        throw new Exception(CGI_RETURNED_ERROR + resp.error_text + " for command " + cmd);
}

From source file:net.paissad.minus.utils.HttpClientUtils.java

/**
 * Convenience method for sending HTTP requests.
 * <b><span style="color:red">Note</span></b>: This method is intended to be
 * used internally, not by end-users./*from   w w  w  . j av  a  2s . c  o m*/
 * 
 * @param baseURL - <b>Example</b>: http://minus.com/api
 * @param parametersBody - The parameters (name => value pairs) to pass to
 *            the request.
 * @param sessionId - If <tt>null</tt> or empty, then create and use a new
 *            session, otherwise, use the specified session_id (which is
 *            stored in a cookie).
 * @param requestType
 * @param additionalRequestHeaders -
 * @param expectedResponseType
 * @return The response retrieved from Minus API.
 * @throws MinusException
 */
private static MinusHttpResponse sendRequest(final String baseURL, final Map<String, String> parametersBody,
        final String sessionId, final RequestType requestType, final Header[] additionalRequestHeaders,
        final ExpectedResponseType expectedResponseType) throws MinusException {

    DefaultHttpClient client = null;
    HttpRequestBase request = null;
    InputStream responseContent = null;
    boolean errorOccured = false;

    try {
        if (requestType == RequestType.GET) {
            request = new HttpGet(baseURL);
            if (parametersBody != null && !parametersBody.isEmpty()) {
                request = appendParametersToRequest(request, parametersBody);
            }

        } else if (requestType == RequestType.POST) {
            UrlEncodedFormEntity encodedEntity = new UrlEncodedFormEntity(getHttpParamsFromMap(parametersBody),
                    HTTP.UTF_8);
            request = new HttpPost(baseURL);
            ((HttpPost) request).setEntity(encodedEntity);

        } else {
            throw new MinusException("The method (" + requestType + ") is unknown, weird ...");
        }

        request.addHeader(new BasicHeader("User-Agent", APP_USER_AGENT));
        if (additionalRequestHeaders != null && additionalRequestHeaders.length > 0) {
            for (Header aHeader : additionalRequestHeaders) {
                request.addHeader(aHeader);
            }
        }

        client = new DefaultHttpClient();
        client.setHttpRequestRetryHandler(new MinusHttpRequestRetryHandler());

        client.getParams().setParameter(ClientPNames.HANDLE_REDIRECTS, true);
        client.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BEST_MATCH);

        CookieStore cookieStore = new BasicCookieStore();

        Cookie sessionCookie = null;
        if (sessionId != null && !sessionId.trim().isEmpty()) {
            sessionCookie = new BasicClientCookie2(MINUS_COOKIE_NAME, sessionId);
            ((BasicClientCookie2) sessionCookie).setPath("/");
            ((BasicClientCookie2) sessionCookie).setDomain(MINUS_DOMAIN_NAME);
            ((BasicClientCookie2) sessionCookie).setVersion(0);
            cookieStore.addCookie(sessionCookie);
        }

        client.setCookieStore(cookieStore);

        HttpContext localContext = new BasicHttpContext();
        // Bind custom cookie store to the local context
        localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);

        // Execute the request ... pass local context as a parameter
        HttpResponse resp = client.execute(request, localContext);

        // Let's update the cookie have the name 'sessionid'
        for (Cookie aCookie : client.getCookieStore().getCookies()) {
            if (aCookie.getName().equals(MINUS_COOKIE_NAME)) {
                sessionCookie = aCookie;
                break;
            }
        }

        Object result = null;
        int statusCode = resp.getStatusLine().getStatusCode();

        if (statusCode == HttpStatus.SC_OK) {
            HttpEntity entity = resp.getEntity();
            if (entity != null) {
                if (expectedResponseType == ExpectedResponseType.STRING) {
                    result = EntityUtils.toString(entity);
                    EntityUtils.consume(entity);
                } else if (expectedResponseType == ExpectedResponseType.HTTP_ENTITY) {
                    result = entity;
                }
            }
        } else {
            // The response code is not OK.
            StringBuilder errMsg = new StringBuilder();
            errMsg.append("HTTP ").append(requestType).append(" failed => ").append(resp.getStatusLine());
            if (request != null) {
                errMsg.append(" : ").append(request.getURI());
            }
            throw new MinusException(errMsg.toString());
        }

        return new MinusHttpResponse(result, sessionCookie);

    } catch (Exception e) {
        errorOccured = true;
        if (request != null) {
            request.abort();
        }
        String errMsg = "Error while executing the HTTP " + requestType + " request : " + e.getMessage();
        throw new MinusException(errMsg, e);

    } finally {
        if (client != null) {
            // We must not close the client is the expected response is an
            // InputStream. Indeed, if ever we close the client, we won't be
            // able to read the response because of SocketException.
            if (errorOccured) {
                client.getConnectionManager().shutdown();
            } else if (expectedResponseType != ExpectedResponseType.HTTP_ENTITY) {
                client.getConnectionManager().shutdown();
            }
        }
        CommonUtils.closeAllStreamsQuietly(responseContent);
    }
}