Example usage for org.apache.http.client.entity UrlEncodedFormEntity UrlEncodedFormEntity

List of usage examples for org.apache.http.client.entity UrlEncodedFormEntity UrlEncodedFormEntity

Introduction

In this page you can find the example usage for org.apache.http.client.entity UrlEncodedFormEntity UrlEncodedFormEntity.

Prototype

public UrlEncodedFormEntity(final Iterable<? extends NameValuePair> parameters) 

Source Link

Document

Constructs a new UrlEncodedFormEntity with the list of parameters with the default encoding of HTTP#DEFAULT_CONTENT_CHARSET

Usage

From source file:com.cybussolutions.wikki.afri_pay.Networking.CheckAmount.java

@Override
protected String doInBackground(String... params) {

    LoginActivity.currentSession.authhttpClient = new DefaultHttpClient();
    HttpContext ctx = new BasicHttpContext();
    ctx.setAttribute(ClientContext.COOKIE_STORE, LoginActivity.currentSession.cookieStore);
    LoginActivity.currentSession.httppost = new HttpPost(
            LoginActivity.currentSession.base_url + "compliance/checkComplianceForTrans/");
    List<BasicNameValuePair> nameValuePairs = new ArrayList<>();
    String id = LoginActivity.currentSession.newProfile.getUserID();
    String sending = LoginActivity.currentSession.newProfile.getCountryID();
    nameValuePairs.add(new BasicNameValuePair("transAmount", params[0]));
    nameValuePairs.add(new BasicNameValuePair("localAmount", params[1]));
    nameValuePairs.add(new BasicNameValuePair("totalAmount", params[2]));
    nameValuePairs.add(new BasicNameValuePair("origenCountry", sending));
    nameValuePairs.add(new BasicNameValuePair("destCountry", params[3]));
    nameValuePairs.add(new BasicNameValuePair("action", "send"));
    nameValuePairs.add(new BasicNameValuePair("originCYY", params[4]));
    nameValuePairs.add(new BasicNameValuePair("destCYY", params[5]));
    nameValuePairs.add(new BasicNameValuePair("customerID", id));

    try {//from w w w.j  av a  2  s. c om
        LoginActivity.currentSession.httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        responsebody = LoginActivity.currentSession.authhttpClient
                .execute(LoginActivity.currentSession.httppost, ctx);
        responseString = new BasicResponseHandler().handleResponse(responsebody);

        if (responseString.equals("1")) {

            return "1";
        }

        else if (responseString.equals("nodocuments%")) {
            String complience;
            complience = "Documents Needed to Proceed this transaction";

            return complience;
        }

        else if (responseString.equals("nodocuments%\n"
                + " Message: Docs Needed Please Go back to manage Documents to Upload missing documents. \n"
                + "Documents Need : Passport OR Driver License - Source of Funds - ")) {

            message = responseString.split("%");

        }

        else {
            message = responseString.split("%");
        }

    } catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return "Exception";
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return "Exception";
    }
    if (responseString.contains("unable to allocate memory for pool") && responseString == null) {

        return "Exception";
    }
    if (responseString.contains("logout")) {
        return "Exception";
    }
    return message[1];
}

From source file:com.klinker.android.spotify.data.AccessToken.java

/**
 * Get a new auth token from spotify by making all of the proper requests
 * @param address the address to direct request to
 * @param token the token from the oauth process
 * @param clientId the client id used to show that Tunes is the accessing app
 * @param clientSecret the client secret used to show that Tunes is the accessing app
 * @param redirectUri where to redirect to once the token has been fetched
 * @param grantType type of request//  w ww.j a va 2 s .  co m
 * @return a JSON object with all of the token information as specified by Spotify
 */
public JSONObject getToken(String address, String token, String clientId, String clientSecret,
        String redirectUri, String grantType) {
    try {
        httpClient = getHttpClient();
        httpPost = new HttpPost(address);
        params.add(new BasicNameValuePair("code", token));
        params.add(new BasicNameValuePair("client_id", clientId));
        params.add(new BasicNameValuePair("client_secret", clientSecret));
        params.add(new BasicNameValuePair("redirect_uri", redirectUri));
        params.add(new BasicNameValuePair("grant_type", grantType));
        httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");
        httpPost.setEntity(new UrlEncodedFormEntity(params));
        HttpResponse httpResponse = executeRequest(httpPost);
        HttpEntity httpEntity = httpResponse.getEntity();
        inputStream = httpEntity.getContent();
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    try {
        BufferedReader reader = getBufferedReader(getInputStreamReader(inputStream));
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        inputStream.close();
        json = sb.toString();
        Log.e("JSONStr", json);
    } catch (Exception e) {
        e.getMessage();
        Log.e("Buffer Error", "Error converting result " + e.toString());
    }

    try {
        jsonObject = createJSON(json);
    } catch (JSONException e) {
        Log.e("JSON Parser", "Error parsing data " + e.toString());
    }

    return jsonObject;
}

From source file:org.skfiy.typhon.spi.auth.p.QihooAuthenticator.java

@Override
public UserInfo authentic(OAuth2 oauth) {
    CloseableHttpClient hc = HC_BUILDER.build();
    HttpPost httpPost = new HttpPost("https://openapi.360.cn/user/me");

    List<NameValuePair> nvps = new ArrayList<>();
    nvps.add(new BasicNameValuePair("access_token", oauth.getCode()));

    try {/*from   www  .  j a  va 2 s.  co m*/

        httpPost.setEntity(new UrlEncodedFormEntity(nvps));
        JSONObject json = hc.execute(httpPost, new ResponseHandler<JSONObject>() {

            @Override
            public JSONObject handleResponse(HttpResponse response)
                    throws ClientProtocolException, IOException {
                String str = StreamUtils.copyToString(response.getEntity().getContent(),
                        StandardCharsets.UTF_8);
                return JSON.parseObject(str);
            }
        });

        if (json.containsKey("error_code")) {
            throw new OAuth2Exception(json.getString("error_code"));
        }

        UserInfo info = new UserInfo();
        info.setUsername(getPlatform().getLabel() + "-" + json.getString("name"));
        info.setPlatform(getPlatform());
        return info;
    } catch (IOException ex) {
        throw new OAuth2Exception("qihoo?", ex);
    } finally {
        try {
            hc.close();
        } catch (IOException ex) {
        }
    }
}

From source file:com.prasanna.android.stacknetwork.service.WriteServiceHelper.java

private Comment writeComment(String restEndPoint, String body) {
    List<BasicNameValuePair> parameters = getBasicNameValuePartListForPost();
    parameters.add(//from   w w w.j  a  v a  2 s . co  m
            new BasicNameValuePair(StackUri.QueryParams.FILTER, QueryParamDefaultValues.ITEM_DETAIL_FILTER));
    parameters.add(new BasicNameValuePair(StackUri.QueryParams.BODY, body));

    Map<String, String> requestHeaders = new HashMap<String, String>();
    requestHeaders.put(HttpHeaderParams.CONTENT_TYPE, HttpContentTypes.APPLICATION_FROM_URL_ENCODED);
    requestHeaders.put(HttpHeaderParams.ACCEPT, HttpContentTypes.APPLICATION_JSON);

    try {
        JSONObjectWrapper jsonObject = executeHttpPostRequest(restEndPoint, requestHeaders, null,
                new UrlEncodedFormEntity(parameters));
        JSONArray jsonArray = jsonObject.getJSONArray(JsonFields.ITEMS);
        if (jsonArray != null && jsonArray.length() == 1)
            return Comment.parse(JSONObjectWrapper.wrap(jsonArray.getJSONObject(0)));
    } catch (UnsupportedEncodingException e) {
        throw new ClientException(ClientException.ClientErrorCode.INVALID_ENCODING);
    } catch (JSONException e) {
        LogWrapper.e(TAG, e.getMessage());
    }
    return null;
}

From source file:com.mothsoft.alexis.util.NetworkingUtil.java

public static HttpClientResponse post(final URL url, final List<NameValuePair> params) throws IOException {
    final HttpPost post = new HttpPost(url.toExternalForm());

    UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(params);
    post.setEntity(formEntity);/*from  www .ja v  a 2s  . co  m*/

    post.addHeader("Accept-Charset", "UTF-8");

    final HttpClient client = getClient();
    HttpResponse response = client.execute(post);
    int status = response.getStatusLine().getStatusCode();

    if (status != 200) {
        throw new IOException("status: " + status);
    }

    final HttpEntity entity = response.getEntity();
    final InputStream is = entity.getContent();
    final Charset charset = getCharset(entity);

    return new HttpClientResponse(post, status, null, null, is, charset);
}

From source file:se.vgregion.pubsub.inttest.Publisher.java

public void publish(URI hub, Feed feed, String... urls) throws URISyntaxException, IOException {
    this.feed = feed;

    HttpPost post = new HttpPost(hub);

    List<NameValuePair> parameters = new ArrayList<NameValuePair>();
    parameters.add(new BasicNameValuePair("hub.mode", "publish"));
    for (String url : urls) {
        parameters.add(new BasicNameValuePair("hub.url", url));
    }/*w  ww  .j a va2  s .co m*/

    post.setEntity(new UrlEncodedFormEntity(parameters));

    DefaultHttpClient client = new DefaultHttpClient();
    HttpResponse response = client.execute(post);

    Assert.assertEquals(204, response.getStatusLine().getStatusCode());
}

From source file:it.av.fac.driver.APIClient.java

public boolean storageRequest(String userToken, JSONObject resource) {
    try (CloseableHttpClient httpclient = HttpClients.createDefault()) {
        HttpPost httpPost = new HttpPost(endpoint + ADMIN_PATH);

        List<NameValuePair> nvps = new ArrayList<>();
        nvps.add(new BasicNameValuePair("resource", URLEncoder.encode(resource.toString(), "UTF-8")));
        nvps.add(new BasicNameValuePair("token", URLEncoder.encode(userToken, "UTF-8")));
        httpPost.setEntity(new UrlEncodedFormEntity(nvps));

        // Create a custom response handler
        ResponseHandler<Boolean> responseHandler = (final HttpResponse response) -> {
            int status = response.getStatusLine().getStatusCode();
            if (status >= 200 && status < 300) {
                return status == 200;
            } else {
                throw new ClientProtocolException("Unexpected response status: " + status);
            }//from   w w w  .  ja v  a 2  s.c  o  m
        };

        return httpclient.execute(httpPost, responseHandler);
    } catch (IOException ex) {
        Logger.getLogger(APIClient.class.getName()).log(Level.SEVERE, null, ex);
        return false;
    }
}

From source file:net.palette_software.pet.restart.HelperHttpClient.java

static void modifyWorker(String targetURL, BalancerManagerManagedWorker w, HashMap<String, Integer> switches,
        int simulation) throws Exception {
    try (CloseableHttpClient client = HttpClients.createDefault()) {

        if (!(simulation < 1)) {
            return;
        }//from  www . jav  a  2s  . c o  m

        //connect to Balancer Manager
        HttpPost httpPost = new HttpPost(targetURL);

        List<NameValuePair> params = new ArrayList<>();

        //check the switches map for the keys are acceptable to interact with Balancer Manager
        for (Map.Entry<String, Integer> entry : switches.entrySet()) {
            String key = entry.getKey();
            String value = entry.getValue().toString();
            if (!BalancerManagerAcceptedPostKeysContains(key)) {
                HelperLogger.loggerStdOut.info("Bad key in modifyWorker (" + key + "," + value + ")");
                continue;
            }
            params.add(new BasicNameValuePair(key, value));
        }

        //add the necessary parameters
        params.add(new BasicNameValuePair("b", w.getBalancerMemberName()));
        params.add(new BasicNameValuePair("w", w.getName()));
        params.add(new BasicNameValuePair("nonce", w.getNonce()));
        httpPost.setEntity(new UrlEncodedFormEntity(params));

        //send the request
        CloseableHttpResponse response = client.execute(httpPost);

        //throw an exception is the result status is abnormal.
        int responseCode = response.getStatusLine().getStatusCode();
        if (200 != responseCode) {
            throw new Exception("Balancer-manager returned a http response of " + responseCode);
        }
    }
}

From source file:org.transdroid.search.HoundDawgs.HoundDawgsAdapter.java

private HttpClient prepareRequest(Context context) throws Exception {

    String username = SettingsHelper.getSiteUser(context, TorrentSite.HoundDawgs);
    String password = SettingsHelper.getSitePass(context, TorrentSite.HoundDawgs);
    if (username == null || password == null) {
        throw new InvalidParameterException(
                "No username or password was provided, while this is required for this private site.");
    }//from   w w w.java 2 s .c  om

    // Setup http client
    HttpClient httpclient = HttpHelper.buildDefaultSearchHttpClient(false);

    // First log in
    HttpPost loginPost = new HttpPost(LOGINURL);
    loginPost.setEntity(new UrlEncodedFormEntity(Arrays.asList(new BasicNameValuePair("username", username),
            new BasicNameValuePair("password", password), new BasicNameValuePair("Login", "login"))));
    HttpResponse loginResult = httpclient.execute(loginPost);
    String loginHtml = HttpHelper.convertStreamToString(loginResult.getEntity().getContent());
    final String LOGIN_ERROR = "<li><a href=\"login.php\">Login</a></li>";
    if (loginResult.getStatusLine().getStatusCode() != HttpStatus.SC_OK
            || loginHtml.indexOf(LOGIN_ERROR) >= 0) {
        // Failed to sign in
        throw new LoginException("Login failure for HoundDawgs with user " + username);
    }

    return httpclient;

}

From source file:io.github.hebra.elasticsearch.beat.meterbeat.device.dlink.DSPW215.java

@Override
public String fetchData() {
    final String url = config.getBaseurl().concat("/my_cgi.cgi?")
            .concat(new BigInteger(130, secureRandom).toString(32));

    try {//from  www. j a  v a2 s.c o m
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(timeout)
                .setConnectTimeout(timeout).setConnectionRequestTimeout(timeout).build();

        HttpClient client = HttpClientBuilder.create().setConnectionTimeToLive(5, TimeUnit.SECONDS)
                .setConnectionReuseStrategy(new NoConnectionReuseStrategy()).build();
        HttpPost post = new HttpPost(url);

        post.setConfig(requestConfig);

        post.setHeader("User-Agent", USER_AGENT);
        post.setHeader("Accept-Language", "en-US,en;q=0.5");

        final List<NameValuePair> urlParameters = new ArrayList<>();
        urlParameters.add(new BasicNameValuePair("request", "create_chklst"));
        post.setEntity(new UrlEncodedFormEntity(urlParameters));

        final HttpResponse response = client.execute(post);

        final String content = IOUtils.toString(response.getEntity().getContent(), Charsets.US_ASCII);

        EntityUtils.consume(response.getEntity());

        return content.split("Meter Watt: ", 2)[1].trim();
    } catch (IOException ioEx) {
        log.error("Timeout when trying to read from {} on {}: {}", config.getName(), config.getBaseurl(),
                ioEx.getMessage());
    }

    return null;
}