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.RestClient.java

public void Execute(RequestMethod method, Context context) throws Exception {
    switch (method) {
    case GET: {/*from  w w w.  ja  va2 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, 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));
        }

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

From source file:com.xyproto.archfriend.Web.java

private HttpClient getNewHttpClient() {
    try {/* ww w  .j  a v  a2 s .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.dhis.smssync.net.MainHttpClient.java

/**
 * Upload SMS to a web service via HTTP POST
 * //w  w w.ja v a2s .c o  m
 * @param address
 * @throws MalformedURLException
 * @throws IOException
 * @return
 */
public static boolean postSmsToWebService(String url, String xml, Context context) {

    Prefrences.loadPreferences(context);
    String encoding = Prefrences.dhisLoginPref;

    // Create a new HttpClient and Post Header
    HttpPost httppost = new HttpPost(url);
    httppost.setHeader("Authorization", "Basic " + encoding);

    try {
        StringEntity se = new StringEntity(xml, HTTP.UTF_8);

        se.setContentType("application/xml");
        httppost.setEntity(se);

        BasicHttpResponse response = (BasicHttpResponse) httpclient.execute(httppost);

        Log.i(CLASS_TAG, "postSmsToWebService(): code: " + response.getStatusLine().getStatusCode() + " xml: "
                + xml + " encoding: " + encoding);

        if (response.getStatusLine().getStatusCode() >= 200 && response.getStatusLine().getStatusCode() < 300) {
            return true;
        } else {
            return false;
        }

    } catch (ClientProtocolException e) {
        return false;
    } catch (IOException e) {
        return false;
    }
}

From source file:com.mockey.ui.UploadConfigurationServlet.java

/**
 * //from  www  . j  ava 2  s  . c  o m
 * 
 * @param req
 *            basic request
 * @param resp
 *            basic resp
 * @throws ServletException
 *             basic
 * @throws IOException
 *             basic
 */
@SuppressWarnings("unchecked")
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    String url = null;
    String definitionsAsString = null;
    String taglistValue = "";

    // ***********************************
    // STEP #1 - READ DATA
    // ***********************************
    if (req.getParameter("viaUrl") != null) {
        url = req.getParameter("url");
        taglistValue = req.getParameter("taglist");
        try {
            InputStream fstream = new URL(url).openStream();
            if (fstream != null) {

                BufferedReader br = new BufferedReader(
                        new InputStreamReader(fstream, Charset.forName(HTTP.UTF_8)));
                StringBuffer inputString = new StringBuffer();
                // Read File Line By Line
                String strLine = null;
                // READ FIRST
                while ((strLine = br.readLine()) != null) {
                    // Print the content on the console
                    inputString.append(new String(strLine.getBytes(HTTP.UTF_8)));
                }
                definitionsAsString = inputString.toString();
            }
        } catch (Exception e) {
            logger.error("Unable to reach url: " + url, e);
            Util.saveErrorMessage("Unable to reach url: " + url, req);
        }
    } else {
        byte[] data = null;
        try {
            // STEP 1. GATHER UPLOADED ITEMS
            // Create a new file upload handler
            DiskFileUpload upload = new DiskFileUpload();

            // Parse the request
            List<FileItem> items = upload.parseRequest(req);
            Iterator<FileItem> iter = items.iterator();
            while (iter.hasNext()) {
                FileItem item = (FileItem) iter.next();

                if (!item.isFormField()) {

                    data = item.get();

                } else {

                    String name = item.getFieldName();
                    if ("taglist".equals(name)) {
                        taglistValue = item.getString();
                    }

                }
            }
            if (data != null && data.length > 0) {
                definitionsAsString = new String(data);
            }
        } catch (Exception e) {
            logger.error("Unable to read or parse file: ", e);
            Util.saveErrorMessage("Unable to upload or parse file.", req);
        }
    }

    // ***********************************
    // STEP #2 - PERSIST DATA
    // ***********************************
    try {

        if (definitionsAsString != null) {
            MockeyXmlFileManager configurationReader = new MockeyXmlFileManager();
            ServiceMergeResults results = configurationReader.loadConfigurationWithXmlDef(definitionsAsString,
                    taglistValue);

            Util.saveSuccessMessage("Service definitions uploaded.", req);
            req.setAttribute("conflicts", results.getConflictMsgs());
            req.setAttribute("additions", results.getAdditionMessages());
        } else {
            Util.saveErrorMessage("Unable to upload or parse empty file.", req);
        }
    } catch (Exception e) {
        Util.saveErrorMessage("Unable to upload or parse file.", req);
    }

    RequestDispatcher dispatch = req.getRequestDispatcher("/upload.jsp");
    dispatch.forward(req, resp);
}

From source file:com.miuidev.themebrowser.RestClient.java

public void Execute(RequestMethod method) throws Exception {
    switch (method) {
    case GET: {/* w  w  w  . j a  v  a2s  . c  om*/
        //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:csic.ceab.movelab.beepath.Fix.java

public boolean uploadJSON(Context context) {

    String response = "";

    String uploadurl = Util.URL_FIXES_JSON;

    try {//w  w w.java2  s  . c o m

        // Create a new HttpClient and Post Header
        HttpPost httppost = new HttpPost(uploadurl);

        HttpParams myParams = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(myParams, 10000);
        HttpConnectionParams.setSoTimeout(myParams, 60000);
        HttpConnectionParams.setTcpNoDelay(myParams, true);

        httppost.setHeader("Content-type", "application/json");
        HttpClient httpclient = new DefaultHttpClient();

        StringEntity se = new StringEntity(exportJSON(context).toString(), HTTP.UTF_8);
        se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
        httppost.setEntity(se);

        // Execute HTTP Post Request

        ResponseHandler<String> responseHandler = new BasicResponseHandler();

        response = httpclient.execute(httppost, responseHandler);

    } catch (ClientProtocolException e) {

    } catch (IOException e) {
    }

    if (response.contains("SUCCESS")) {

        return true;
    } else {
        return false;
    }

}

From source file:org.lol.reddit.account.RedditAccount.java

public static LoginResultPair login(final Context context, final String username, final String password,
        final HttpClient client) {

    final ArrayList<NameValuePair> fields = new ArrayList<NameValuePair>(3);
    fields.add(new BasicNameValuePair("user", username));
    fields.add(new BasicNameValuePair("passwd", password));
    fields.add(new BasicNameValuePair("api_type", "json"));

    // TODO put somewhere else
    final HttpParams params = new BasicHttpParams();
    params.setParameter(CoreProtocolPNames.USER_AGENT, Constants.ua(context));
    params.setParameter(CoreConnectionPNames.SO_TIMEOUT, 20000); // TODO remove hardcoded params, put in network prefs
    params.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 20000);
    params.setParameter(CoreConnectionPNames.MAX_HEADER_COUNT, 100);
    params.setParameter(ClientPNames.HANDLE_REDIRECTS, true);
    params.setParameter(ClientPNames.MAX_REDIRECTS, 5);

    final HttpPost request = new HttpPost("https://ssl.reddit.com/api/login");
    request.setParams(params);// w  w w.  ja  v a  2  s . c o m

    try {
        request.setEntity(new UrlEncodedFormEntity(fields, HTTP.UTF_8));
    } catch (UnsupportedEncodingException e) {
        return new LoginResultPair(LoginResult.INTERNAL_ERROR);
    }

    final PersistentCookieStore cookies = new PersistentCookieStore();

    final HttpContext localContext = new BasicHttpContext();
    localContext.setAttribute(ClientContext.COOKIE_STORE, cookies);

    final StatusLine status;
    final HttpEntity entity;
    try {
        final HttpResponse response = client.execute(request, localContext);
        status = response.getStatusLine();
        entity = response.getEntity();

    } catch (IOException e) {
        return new LoginResultPair(LoginResult.CONNECTION_ERROR);
    }

    if (status.getStatusCode() != 200) {
        return new LoginResultPair(LoginResult.REQUEST_ERROR);
    }

    final JsonValue result;

    try {
        result = new JsonValue(entity.getContent());
        result.buildInThisThread();
    } catch (IOException e) {
        return new LoginResultPair(LoginResult.CONNECTION_ERROR);
    }

    final String modhash;

    try {

        // TODO use the more general reddit error finder
        final JsonBufferedArray errors = result.asObject().getObject("json").getArray("errors");
        errors.join();
        if (errors.getCurrentItemCount() != 0) {

            for (final JsonValue v : errors) {
                for (final JsonValue s : v.asArray()) {

                    // TODO handle unknown messages by concatenating all Reddit's strings

                    if (s.getType() == JsonValue.Type.STRING) {

                        Log.i("RR DEBUG ERROR", s.asString());

                        // lol, reddit api
                        if (s.asString().equalsIgnoreCase("WRONG_PASSWORD")
                                || s.asString().equalsIgnoreCase("invalid password")
                                || s.asString().equalsIgnoreCase("passwd"))
                            return new LoginResultPair(LoginResult.WRONG_PASSWORD);

                        if (s.asString().contains("too much")) // also "RATELIMIT", but that's not as descriptive
                            return new LoginResultPair(LoginResult.RATELIMIT, s.asString());
                    }
                }
            }

            return new LoginResultPair(LoginResult.UNKNOWN_REDDIT_ERROR);
        }

        final JsonBufferedObject data = result.asObject().getObject("json").getObject("data");

        modhash = data.getString("modhash");

    } catch (NullPointerException e) {
        return new LoginResultPair(LoginResult.JSON_ERROR);
    } catch (InterruptedException e) {
        return new LoginResultPair(LoginResult.JSON_ERROR);
    } catch (IOException e) {
        return new LoginResultPair(LoginResult.JSON_ERROR);
    }

    return new LoginResultPair(LoginResult.SUCCESS, new RedditAccount(username, modhash, cookies, 0), null);
}

From source file:com.expensify.testframework.RestClient.java

public void execute(RequestMethod method) throws Exception {
    switch (method) {
    case GET: {/*  w ww.j a v  a2  s.c om*/
        //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 (null != jsonString) {
            request.setEntity(new StringEntity(jsonString));
        }
        if (!params.isEmpty()) {
            request.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
        }

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

From source file:org.craftercms.social.util.UGCHttpClient.java

private HttpPost manageAttachments(String[] attachments, String ticket, String target, String textContent)
        throws UnsupportedEncodingException, URISyntaxException {
    List<NameValuePair> qparams = new ArrayList<NameValuePair>();
    qparams.add(new BasicNameValuePair("ticket", ticket));
    URI uri = URIUtils.createURI(scheme, host, port, appPath + "/api/2/ugc/" + "create.json",
            URLEncodedUtils.format(qparams, HTTP.UTF_8), null);
    HttpPost httppost = new HttpPost(uri);

    if (attachments.length > 0) {

        MultipartEntity me = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
        File file;/*from   w w w  .ja v  a  2  s.c om*/
        FileBody fileBody;
        for (String f : attachments) {
            file = new File(f);
            fileBody = new FileBody(file, "application/octect-stream");
            me.addPart("attachments", fileBody);
        }
        //File file = new File(attachments[0]);
        //FileBody fileBody = new FileBody(file, "application/octect-stream") ;
        //me.addPart("attachments", fileBody) ;
        me.addPart("target", new StringBody(target));
        me.addPart("textContent", new StringBody(textContent));

        httppost.setEntity(me);
    }
    return httppost;
}

From source file:com.jigarmjoshi.service.RestService.java

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