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:org.owasp.goatdroid.herdfinancial.requestresponse.AuthenticatedRestClient.java

public void Execute(RequestMethod method, Context context) throws Exception {
    switch (method) {
    case GET: {/* ww w  . j  a  va  2  s  .c o  m*/
        // add parameters
        String combinedParams = "";
        if (!params.isEmpty()) {
            combinedParams += "?";
            for (NameValuePair p : params) {
                String paramString = p.getName() + "=" + URLEncoder.encode(p.getValue(), "UTF-8");
                if (combinedParams.length() > 1) {
                    combinedParams += "&" + paramString;
                } else {
                    combinedParams += paramString;
                }
            }
        }

        HttpGet request = new HttpGet(url + combinedParams);

        // add headers
        for (NameValuePair h : headers) {
            request.addHeader(h.getName(), h.getValue());
        }
        request.addHeader("Cookie", "AUTH=" + sessionToken);

        executeRequest(request, url, context);
        break;
    }
    case POST: {
        HttpPost request = new HttpPost(url);
        // add headers
        for (NameValuePair h : headers) {
            request.addHeader(h.getName(), h.getValue());
        }

        if (!params.isEmpty()) {
            request.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
        }
        request.addHeader("Cookie", "AUTH=" + sessionToken);

        executeRequest(request, url, context);
        break;
    }
    }
}

From source file:org.que.async.AsyncGETRequester.java

@Override
protected List<JSONObject> doInBackground(GetRequestInfo... urls) {
    List<JSONObject> result = new ArrayList<JSONObject>();
    if (urls != null) {
        for (int i = 0; i < urls.length; i++) {
            String url = urls[i].getUrl();
            if (url != null) {
                HttpGet get = new HttpGet(url);
                String etag = urls[i].getEtag();
                if (etag != null && !etag.isEmpty()) {
                    get.setHeader(HEADER_IF_NONE_MATCH, etag);
                }//from w  ww  .  j  ava 2 s .  com

                if (credentials != null) {
                    get.addHeader(BasicScheme.authenticate(credentials, HTTP.UTF_8, false));
                }
                executeGetRequest(get, result);
            }
        }
    }
    return result;
}

From source file:com.lgallardo.qbittorrentclient.RSSFeedParser.java

public RSSFeed getRSSFeed(String channelTitle, String channelUrl, String filter) {

    // Decode url link
    try {//ww w.j av a 2  s  .c o  m
        channelUrl = URLDecoder.decode(channelUrl, "UTF-8");
    } catch (UnsupportedEncodingException e) {
        Log.e("Debug", "RSSFeedParser - decoding error: " + e.toString());
    }

    // Parse url
    Uri uri = uri = Uri.parse(channelUrl);
    ;
    int event;
    String text = null;
    String torrent = null;
    boolean header = true;

    // TODO delete itemCount, as it's not really used
    this.itemCount = 0;

    HttpResponse httpResponse;
    DefaultHttpClient httpclient;

    XmlPullParserFactory xmlFactoryObject;
    XmlPullParser xmlParser = null;

    HttpParams httpParameters = new BasicHttpParams();

    // Set the timeout in milliseconds until a connection is established.
    // The default value is zero, that means the timeout is not used.
    int timeoutConnection = connection_timeout * 1000;

    // Set the default socket timeout (SO_TIMEOUT)
    // in milliseconds which is the timeout for waiting for data.
    int timeoutSocket = data_timeout * 1000;

    // Set http parameters
    HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
    HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
    HttpProtocolParams.setUserAgent(httpParameters, "qBittorrent for Android");
    HttpProtocolParams.setVersion(httpParameters, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(httpParameters, HTTP.UTF_8);

    RSSFeed rssFeed = new RSSFeed();
    rssFeed.setChannelTitle(channelTitle);
    rssFeed.setChannelLink(channelUrl);

    httpclient = null;

    try {

        // Making HTTP request
        HttpHost targetHost = new HttpHost(uri.getAuthority());

        // httpclient = new DefaultHttpClient(httpParameters);
        // httpclient = new DefaultHttpClient();
        httpclient = getNewHttpClient();

        httpclient.setParams(httpParameters);

        //            AuthScope authScope = new AuthScope(targetHost.getHostName(), targetHost.getPort());
        //            UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(this.username, this.password);
        //
        //            httpclient.getCredentialsProvider().setCredentials(authScope, credentials);

        // set http parameters

        HttpGet httpget = new HttpGet(channelUrl);

        httpResponse = httpclient.execute(targetHost, httpget);

        StatusLine statusLine = httpResponse.getStatusLine();

        int mStatusCode = statusLine.getStatusCode();

        if (mStatusCode != 200) {
            httpclient.getConnectionManager().shutdown();
            throw new JSONParserStatusCodeException(mStatusCode);
        }

        HttpEntity httpEntity = httpResponse.getEntity();
        is = httpEntity.getContent();

        xmlFactoryObject = XmlPullParserFactory.newInstance();
        xmlParser = xmlFactoryObject.newPullParser();

        xmlParser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false);
        xmlParser.setInput(is, null);

        event = xmlParser.getEventType();

        // Get Channel info
        String name;
        RSSFeedItem item = null;
        ArrayList<RSSFeedItem> items = new ArrayList<RSSFeedItem>();

        // Get items
        while (event != XmlPullParser.END_DOCUMENT) {

            name = xmlParser.getName();

            switch (event) {
            case XmlPullParser.START_TAG:

                if (name != null && name.equals("item")) {
                    header = false;
                    item = new RSSFeedItem();
                    itemCount = itemCount + 1;
                }

                try {
                    for (int i = 0; i < xmlParser.getAttributeCount(); i++) {

                        if (xmlParser.getAttributeName(i).equals("url")) {
                            torrent = xmlParser.getAttributeValue(i);

                            if (torrent != null) {
                                torrent = Uri.decode(URLEncoder.encode(torrent, "UTF-8"));
                            }
                            break;
                        }
                    }
                } catch (Exception e) {

                }

                break;

            case XmlPullParser.TEXT:
                text = xmlParser.getText();
                break;

            case XmlPullParser.END_TAG:

                if (name.equals("title")) {
                    if (!header) {
                        item.setTitle(text);
                        //                                Log.d("Debug", "PARSER - Title: " + text);
                    }
                } else if (name.equals("description")) {
                    if (header) {
                        //                                Log.d("Debug", "Channel Description: " + text);
                    } else {
                        item.setDescription(text);
                        //                                Log.d("Debug", "Description: " + text);
                    }
                } else if (name.equals("link")) {
                    if (!header) {
                        item.setLink(text);
                        //                                Log.d("Debug", "Link: " + text);
                    }

                } else if (name.equals("pubDate")) {

                    // Set item pubDate
                    if (item != null) {
                        item.setPubDate(text);
                    }

                } else if (name.equals("enclosure")) {
                    item.setTorrentUrl(torrent);
                    //                            Log.d("Debug", "Enclosure: " + torrent);
                } else if (name.equals("item") && !header) {

                    if (items != null & item != null) {

                        // Fix torrent url for no-standard rss feeds
                        if (torrent == null) {

                            String link = item.getLink();

                            if (link != null) {
                                link = Uri.decode(URLEncoder.encode(link, "UTF-8"));
                            }

                            item.setTorrentUrl(link);
                        }

                        items.add(item);
                    }

                }

                break;
            }

            event = xmlParser.next();

            //                if (!header) {
            //                    items.add(item);
            //                }

        }

        // Filter items

        //            Log.e("Debug", "RSSFeedParser - filter: >" + filter + "<");
        if (filter != null && !filter.equals("")) {

            Iterator iterator = items.iterator();

            while (iterator.hasNext()) {

                item = (RSSFeedItem) iterator.next();

                // If link doesn't match filter, remove it
                //                    Log.e("Debug", "RSSFeedParser - item no filter: >" + item.getTitle() + "<");

                Pattern patter = Pattern.compile(filter);

                Matcher matcher = patter.matcher(item.getTitle()); // get a matcher object

                if (!(matcher.find())) {
                    iterator.remove();
                }

            }
        }

        rssFeed.setItems(items);
        rssFeed.setItemCount(itemCount);
        rssFeed.setChannelPubDate(items.get(0).getPubDate());
        rssFeed.setResultOk(true);

        is.close();
    } catch (Exception e) {
        Log.e("Debug", "RSSFeedParser - : " + e.toString());
        rssFeed.setResultOk(false);
    } finally {
        // When HttpClient instance is no longer needed,
        // shut down the connection manager to ensure
        // immediate deallocation of all system resources
        if (httpclient != null) {
            httpclient.getConnectionManager().shutdown();
        }
    }

    // return JSON String
    return rssFeed;

}

From source file:edu.cwru.apo.RestClient.java

public void Execute() throws Exception {
    switch (requestType) {
    case GET: {/*w  ww .j a  v  a2s. c o m*/
        //add parameters
        String combinedParams = "";
        if (!params.isEmpty()) {
            combinedParams += "?";
            for (NameValuePair p : params) {
                String paramString = p.getName() + "=" + URLEncoder.encode(p.getValue(), "UTF-8");
                if (combinedParams.length() > 1) {
                    combinedParams += "&" + paramString;
                } else {
                    combinedParams += paramString;
                }
            }
        }

        HttpGet request = new HttpGet(url + combinedParams);

        //add headers
        for (NameValuePair h : headers) {
            request.addHeader(h.getName(), h.getValue());
        }

        executeRequest(request, url);
        break;
    }
    case POST: {
        HttpPost request = new HttpPost(url);

        //add headers
        for (NameValuePair h : headers) {
            request.addHeader(h.getName(), h.getValue());
        }

        if (!params.isEmpty()) {
            request.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
        }

        executeRequest(request, url);
        break;
    }
    }
}

From source file:com.vkassin.mtrade.CSPLicense.java

public HttpClient getNewHttpClient() {
    try {//w  ww .  ja va  2s . c o m

        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null, null);
        SSLSocketFactory sf = new MySSLSocketFactory(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:org.puremvc.java.demos.android.currencyconverter.converter.model.HttpCall.java

/**
  * Pull the raw text content of the given URL. This call blocks until the
  * operation has completed, and is synchronized because it uses a shared
  * buffer {@link #buffer}.//www  .  j  a  v  a2  s  .  c om
  *
  * @throws ApiException
  *       If any connection or server error occurs.
  * 
  * @throws URISyntaxException
  *       If the <code>URI</code> string is invalid.
  */
public synchronized void load() throws ApiException {
    if (closed)
        return;

    if (uri == null)
        throw new ApiException("Target URI of the call must be set");

    //Set the URI
    try {
        request.setURI(new URI(uri));
    } catch (URISyntaxException e) {
        throw new ApiException("Target URI of the call is malformed");
    }

    //Add headers
    for (int i = 0; i < headers.size(); i++) {
        NameValuePair pair = headers.get(i);
        request.addHeader(pair.getName(), pair.getName());
    }

    try {
        request.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
    } catch (UnsupportedEncodingException e1) {
        throw new ApiException("Problem adding parameters to the call", e1);
    }

    //Execute the call
    try {
        HttpResponse response = httpClient.execute(request);

        // Check if server response is valid
        StatusLine status = response.getStatusLine();
        if (status.getStatusCode() != HTTP_STATUS_OK)
            throw new ApiException("Invalid response from server: " + status.toString());

        // Pull content stream from response
        entity = response.getEntity();
        inputStream = entity.getContent();
    } catch (IllegalArgumentException e2) {
        throw new ApiException("Problem executing call", e2);
    } catch (IllegalStateException e2) {
        throw new ApiException("Problem calling server", e2);
    } catch (UnknownHostException e2) {
        throw new ApiException("Unknown host: " + uri, e2);
    } catch (IOException e2) {
        throw new ApiException("Problem communicating with server", e2);
    }

    result = new ByteArrayOutputStream();
}

From source file:org.freeeed.data.index.SolrIndex.java

protected void sendPostCommand(String point, String param) throws SolrException {
    HttpClient httpClient = new DefaultHttpClient();

    try {//from   w  w w  .  j  a v a 2  s  .c om
        HttpPost request = new HttpPost(point);
        StringEntity params = new StringEntity(param, HTTP.UTF_8);
        params.setContentType("text/xml");

        request.setEntity(params);

        HttpResponse response = httpClient.execute(request);
        if (response.getStatusLine().getStatusCode() != 200) {
            logger.error("Solr Invalid Response: {}", response.getStatusLine().getStatusCode());
            logger.error(response.getStatusLine().toString());
            HttpEntity entity = response.getEntity();
            String responseString = EntityUtils.toString(entity, "UTF-8");
            logger.error(responseString);
            logger.error("point:");
            logger.error(point);
            logger.error("param");
            logger.error(param);
        }
    } catch (Exception ex) {
        logger.error("Problem sending request", ex);
    }
}

From source file:mobisocial.metrics.UsageMetrics.java

public void report(Throwable exception) {
    if (mLevel == ReportingLevel.DISABLED || UsageMetrics.CHIRP_REPORTING_ENDPOINT == null) {
        return;/*from   ww  w.j a  v  a 2s.com*/
    }
    Message msg = mReportingThread.mHandler.obtainMessage(ReportingHandler.HTTP_REQUEST);
    HttpPost post = new HttpPost(UsageMetrics.CHIRP_REPORTING_ENDPOINT);
    List<NameValuePair> data = new ArrayList<NameValuePair>();
    JSONObject json = MusubiExceptionHandler.jsonForException(mContext, exception, true);
    data.add(new BasicNameValuePair("json", json.toString()));
    try {
        post.setEntity(new UrlEncodedFormEntity(data, HTTP.UTF_8));
        msg.obj = post;
        mReportingThread.mHandler.sendMessage(msg);
    } catch (IOException e) {
    }
}

From source file:com.todoroo.astrid.service.abtesting.ABTestInvoker.java

/**
 * Converts the JSONArray payload into an HTTPEntity suitable for
 * POSTing.//  w ww .  ja  va2 s  . com
 * @param payload
 * @return
 */
private HttpEntity createPostData(JSONArray payload) throws IOException {
    List<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new BasicNameValuePair("apikey", API_KEY));

    if (payload != null)
        params.add(new BasicNameValuePair("payload", payload.toString()));

    StringBuilder sigBuilder = new StringBuilder();
    for (NameValuePair entry : params) {
        if (entry.getValue() == null)
            continue;

        String key = entry.getName();
        String value = entry.getValue();

        sigBuilder.append(key).append(value);
    }

    sigBuilder.append(API_SECRET);
    String signature = DigestUtils.md5Hex(sigBuilder.toString());
    params.add(new BasicNameValuePair("sig", signature));

    try {
        return new UrlEncodedFormEntity(params, HTTP.UTF_8);
    } catch (UnsupportedEncodingException e) {
        throw new IOException("Unsupported URL encoding");
    }
}

From source file:com.optimusinfo.elasticpath.cortex.authentication.AsyncTaskAuthentication.java

@Override
protected String doInBackground(Void... params) {
    String responseJson = null;/*from  w w w . j av a2 s  .  co  m*/
    try {
        // Create the HTTP post Request
        List<NameValuePair> parameters = new ArrayList<NameValuePair>();
        // Add grant type
        parameters.add(new BasicNameValuePair(Constants.Authentication.HEADER_GRANT_TYPE, "password"));
        // Add user name only if provided
        if (mUsername != null && mUsername.length() != 0) {
            parameters.add(new BasicNameValuePair(Constants.Authentication.HEADER_USERNAME, mUsername));
        }
        // Add pass word only if provided
        if (mPassword != null && mPassword.length() != 0) {
            parameters.add(new BasicNameValuePair(Constants.Authentication.HEADER_PASSWORD, mPassword));
        }
        // Add scope header
        parameters.add(new BasicNameValuePair(Constants.Authentication.HEADER_SCOPE, mScope));
        // Add role header
        parameters.add(new BasicNameValuePair(Constants.Authentication.HEADER_ROLE, mRole));
        // Post the Request
        UrlEncodedFormEntity objEntity = new UrlEncodedFormEntity(parameters, HTTP.UTF_8);

        responseJson = Utils.postData(mCortexUrl.concat(Constants.Routes.AUTH_ROUTE), objEntity,
                Constants.Config.CONTENT_TYPE);

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }
    return responseJson;
}