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:com.phonty.improved.Register.java

public boolean process(String phone) {
    String line = null;//w  w w .  jav  a2  s .  c  om
    StringBuilder builder = new StringBuilder();
    try {
        String token = Installation.id(context);
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair("phone", phone));
        nvps.add(new BasicNameValuePair("token", token));

        httppost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
        HttpResponse response = client.execute(httppost);

        StatusLine statusLine = response.getStatusLine();
        int statusCode = statusLine.getStatusCode();
        if (statusCode == 200) {
            HttpEntity entity = response.getEntity();
            InputStream content = entity.getContent();
            BufferedReader reader = new BufferedReader(new InputStreamReader(content));
            while ((line = reader.readLine()) != null) {
                builder.append(line);
                if (parse(line).equals("OK"))
                    return true;
                else
                    return false;
            }
        } else {
        }
    } catch (ClientProtocolException e) {
        e.printStackTrace();
        return false;
    } catch (IOException e) {
        e.printStackTrace();
        return false;
    }
    return false;
}

From source file:androidmapsdefinitivo.android.bajaintec.com.androidmapsdefinitivo.Control.RestClient.java

public void Execute(RequestMethod method) throws Exception {
    switch (method) {
    case GET: {/*  ww w  .j av  a  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());
        }

        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;
    }
    }

    Log.d("WEBSERVICE", response);
}

From source file:com.googlesource.gerrit.plugins.hooks.rtc.network.Transport.java

public <T> T patch(final String path, final Type typeOrClass, JsonObject data, String etag) throws IOException {
    HttpPatch request = newHttpPatch(path);
    if (log.isDebugEnabled())
        log.debug("Preparing PATCH against " + request.getURI() + " using etag " + etag + " and data " + data);
    request.setEntity(new StringEntity(data.toString(), HTTP.UTF_8));
    if (etag != null)
        request.addHeader("If-Match", etag);
    return invoke(request, typeOrClass, APP_OSLC, APP_OSLC);
}

From source file:de.escidoc.core.test.aa.UserGroupTestBase.java

/**
 * Test activating an UserGroup.//  w  w w.j a  v  a  2s.  co m
 *
 * @param id           The id of the UserGroup.
 * @param taskParamXml The task parameter in an XML structure.
 * @return userGroup-XML
 * @throws Exception If anything fails.
 */
protected String activate(final String id, final String taskParamXml) throws Exception {

    Object result = getUserGroupClient().activate(id, taskParamXml);
    String xmlResult = null;
    if (result instanceof HttpResponse) {
        HttpResponse method = (HttpResponse) result;
        xmlResult = EntityUtils.toString(method.getEntity(), HTTP.UTF_8);
        assertHttpStatusOfMethod("", method);
        if (xmlResult.equals("")) {
            xmlResult = null;
        }

    } else if (result instanceof String) {
        xmlResult = (String) result;
    }
    return xmlResult;
}

From source file:com.figo.campaignhelper.GenerateActivity.java

private static String guessAppropriateEncoding(CharSequence contents) {
    // Very crude at the moment
    for (int i = 0; i < contents.length(); i++) {
        if (contents.charAt(i) > 0xFF) {
            return HTTP.UTF_8;
        }//from  ww  w  .  java 2s .co  m
    }
    return null;
}

From source file:com.arthurassuncao.cepview.net.ClienteHttp.java

public void executar() {
    try {/*from   ww  w.j  av a  2s  . c o m*/
        if (this.httpRequest instanceof HttpGet) {
            resposta = cliente.execute(this.httpRequest);
        } else if (this.httpRequest instanceof HttpPost) {
            UrlEncodedFormEntity urlParametros = new UrlEncodedFormEntity(parametros, HTTP.UTF_8);
            ((HttpPost) this.httpRequest).setEntity(urlParametros);
            resposta = cliente.execute(this.httpRequest);
        } else {
            new IllegalArgumentException("Tipo de requisio invlido");
        }
    } catch (Exception e) {
        Log.d("erro", e.toString());
        resposta = null;
    }
}

From source file:com.cellobject.oikos.util.NetworkHelper.java

public HttpClient createHttpClient() {
    try {/*  w  w  w  . j a v a  2 s . c om*/
        final KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null, null);
        final SSLSocketFactory sf = new IISSLSocketFactory(trustStore);
        sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        final HttpParams params = new BasicHttpParams();
        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
        final SchemeRegistry registry = new SchemeRegistry();
        registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
        registry.register(new Scheme("https", sf, 443));
        final ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);
        return new DefaultHttpClient(ccm, params);
    } catch (final Exception e) {
        return new DefaultHttpClient();
    }
}

From source file:eu.nubomedia.nubomedia_kurento_health_communicator_android.kc_and_communicator.services.CommandService.java

private static HttpResp<Void> sendCommandWithMedia(final Context ctx, CommandObject cmd)
        throws KurentoCommandException, TransportException, InvalidDataException, NotFoundException {
    String contentPath = cmd.getMedia();

    File content = new File(contentPath);
    String mimeType;/* w  w w . j a  va 2s.c o  m*/
    if (content.exists() && content.isFile()) {
        if (contentPath.contains(ConstantKeys.EXTENSION_JPG)) {
            mimeType = ConstantKeys.TYPE_IMAGE;
        } else {
            mimeType = ConstantKeys.TYPE_VIDEO;
        }
    } else {
        String error = contentPath + " does not exists or is not a file";
        log.error(error);
        throw new KurentoCommandException(error);
    }

    CustomMultiPartEntity mpEntity;
    final String json = cmd.getJson();
    String charset = HTTP.UTF_8;
    long contentSize = 0;
    try {
        contentSize = content.length();
        /* Aprox. total size */
        final long totalSize = content.length() + json.getBytes("UTF-16BE").length;
        mpEntity = new CustomMultiPartEntity(new CustomMultiPartEntity.ProgressListener() {

            private int i;

            @Override
            public void transferred(long num) {
                int totalpercent = Math.min(100, (int) ((num * 100) / totalSize));

                if (totalpercent > (1 + PERCENT_INC * i) || totalpercent >= 100) {
                    Intent intent = new Intent();
                    intent.setAction(ConstantKeys.BROADCAST_PROGRESSBAR);
                    intent.putExtra(ConstantKeys.JSON, json);
                    intent.putExtra(ConstantKeys.TOTAL, totalpercent);
                    ctx.sendBroadcast(intent);
                    i++;
                }
            }
        });

        mpEntity.addPart(COMMAND_PART_NAME,
                new StringBody(json, HttpManager.CONTENT_TYPE_APPLICATION_JSON, Charset.forName(charset)));

        FormBodyPart fbp = new FormBodyPart(CONTENT_PART_NAME, new FileBody(content, mimeType));
        fbp.addField(HTTP.CONTENT_LEN, String.valueOf(contentSize));
        mpEntity.addPart(fbp);

    } catch (UnsupportedEncodingException e) {
        String msg = "Cannot use " + charset + "as entity";
        log.error(msg, e);
        throw new TransportException(msg);
    }

    return HttpManager.sendPostVoid(ctx, ctx.getString(R.string.url_command), mpEntity);
}

From source file:org.eclipse.lyo.testsuite.server.trsutils.RDFModelResponseHandler.java

@Override
public Model handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
    authTypes = response.getHeaders("WWW-Authenticate");
    statusCode = response.getStatusLine().getStatusCode();
    reason = response.getStatusLine().getReasonPhrase();
    Model model = ModelUtil.createDefaultModel();
    HttpEntity entity = response.getEntity();
    try {//from ww w  . j a v a2 s  . c o  m
        if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
            HttpErrorHandler.responseToException(response);
        }

        if (entity == null)

            throw new InvalidRDFResourceException(
                    MessageFormat.format(Messages.getServerString("rdf.model.response.helper.missing.rdf"), //$NON-NLS-1$
                            base.getURI()));

        String rdfFormat = null;
        final Header contentTypeHeader = response.getFirstHeader(HttpConstants.CONTENT_TYPE);
        if (contentTypeHeader != null) {
            final ContentType contentType = ContentType.parse(contentTypeHeader.getValue());
            if (contentType != null) {
                Lang lang = WebContent.contentTypeToLang(contentType.getContentType());
                if (lang != null) {
                    rdfFormat = lang.getName();
                } else if (HttpConstants.CT_TEXT_XML.equals(contentType.getContentType())) {
                    rdfFormat = Lang.RDFXML.getName(); // attempt RDF
                    // parsing anyway
                }
            }
        }

        if (rdfFormat == null)
            throw new ClientProtocolException(
                    MessageFormat.format(Messages.getServerString("rdf.model.response.helper.bad.content.type"), //$NON-NLS-1$
                            base.getURI()));

        String content = EntityUtils.toString(entity, HTTP.UTF_8);
        try {
            model.read(new StringReader(content), base.getURI(), rdfFormat);
        } catch (Exception e) {
            if (e.getMessage().contains("Interrupt") //$NON-NLS-1$
                    || Thread.currentThread().isInterrupted()) {
                Thread.currentThread().interrupt();
                throw (IOException) new IOException().initCause(e);
            }

            throw new InvalidRDFResourceException(
                    MessageFormat.format(Messages.getServerString("rdf.model.response.helper.unparseable.rdf"), //$NON-NLS-1$
                            base.getURI(), content),
                    e);
        }

        HttpResponseUtil.finalize(response);
    } finally {
        try {
            if (entity != null) {
                EntityUtils.consume(entity);
            }
        } catch (IOException e) {
            // ignore
        }
    }
    return model;
}

From source file:com.fanfou.app.opensource.service.DownloadService.java

public static AppVersionInfo fetchVersionInfo() {
    final SimpleClient client = new SimpleClient(AppContext.getAppContext());
    try {/* ww  w . j  a  v  a2  s .c  om*/
        final HttpResponse response = client.get(DownloadService.UPDATE_VERSION_FILE);
        final int statusCode = response.getStatusLine().getStatusCode();
        if (AppContext.DEBUG) {
            Log.d(DownloadService.TAG, "statusCode=" + statusCode);
        }
        if (statusCode == 200) {
            final String content = EntityUtils.toString(response.getEntity(), HTTP.UTF_8);
            if (AppContext.DEBUG) {
                Log.d(DownloadService.TAG, "response=" + content);
            }
            return AppVersionInfo.parse(content);
        }
    } catch (final IOException e) {
        if (AppContext.DEBUG) {
            e.printStackTrace();
        }
    } catch (final Exception e) {
        if (AppContext.DEBUG) {
            e.printStackTrace();
        }
    } finally {
    }
    return null;
}