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, final Charset charset) 

Source Link

Document

Constructs a new UrlEncodedFormEntity with the list of parameters in the specified encoding.

Usage

From source file:com.qingzhi.apps.fax.client.NetworkUtilities.java

private static String executeGet(String url, Map<String, String> map) throws IOException {

    HttpClient httpclient = new DefaultHttpClient();
    HttpParams params = httpclient.getParams();
    HttpConnectionParams.setConnectionTimeout(params, HTTP_CONNECTION_TIMEOUT);
    HttpConnectionParams.setSoTimeout(params, HTTP_SO_TIMEOUT);

    HttpPost post = new HttpPost(url);

    ArrayList<BasicNameValuePair> postDate = new ArrayList<BasicNameValuePair>();
    Set<String> set = map.keySet();
    Iterator<String> iterator = set.iterator();
    while (iterator.hasNext()) {
        String key = iterator.next();
        postDate.add(new BasicNameValuePair(key, map.get(key)));
    }/*from   ww  w . j a  v  a  2 s .  co  m*/
    post.setEntity(new UrlEncodedFormEntity(postDate, HTTP.UTF_8));
    HttpResponse httpResponse = httpclient.execute(post);
    throwErrors(httpResponse);

    HttpEntity httpEntity = httpResponse.getEntity();
    if (httpEntity != null) {
        String response = EntityUtils.toString(httpEntity);
        LOGD(TAG, response);
        return response;
    }
    return null;
}

From source file:org.opencastproject.remotetest.server.EngageModuleTest.java

private void clearSearchIndex() throws Exception {
    HttpPost post = new HttpPost(BASE_URL + "/search/clear");

    List<NameValuePair> formParams = new ArrayList<NameValuePair>();
    post.setEntity(new UrlEncodedFormEntity(formParams, "UTF-8"));

    client.execute(post);/*from  w w  w  .ja v a2  s  .  c o m*/
}

From source file:org.datacleaner.util.http.HttpXmlUtils.java

public String getUrlContent(String url, Map<String, String> params) throws IOException {
    if (params == null) {
        params = Collections.emptyMap();
    }/* ww  w.j  a va2 s  .c om*/
    logger.info("getUrlContent({},{})", url, params);
    HttpPost method = new HttpPost(url);
    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
    for (Entry<String, String> entry : params.entrySet()) {
        nameValuePairs.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
    }
    method.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8"));
    ResponseHandler<String> responseHandler = new BasicResponseHandler();
    String response = getHttpClient().execute(method, responseHandler);
    return response;
}

From source file:com.shareplaylearn.resources.OAuth.java

/**
 * Callback for Google Oauth. Google calls this endpoint with the information
 * needed to make yet another callback to google which returns the user token.
 * When that information is returned, this resource then redirects back to the
 * configured OAUTH_REDIRECT_LOCATION (set in the AuthService class)
 *
 * Sample returned URL:/*from www.j  av a  2 s . c  o  m*/
 * http://www.shareplaylearn.com/SharePlayLearn2/api/oauth2callback?
 * state=insecure_test_token
 * &code=4/1Oxqgx2PRd8y4YxC7ByfJOLNiN-2.4hTyImQWEVMREnp6UAPFm0EEMmr5kAI
 * &authuser=0&num_sessions=1
 * &prompt=consent
 * &session_state=3dd372aa714b1b2313a838f8c4a4145b928da51f..8b83
 * @return an instance of java.lang.String
 */
public static String GoogleOauthCallback(Request req, Response res) {
    String clientState = req.queryParams("state");
    String authCode = req.queryParams("code");
    String sessionState = req.queryParams("session_state");
    HttpPost tokenPost = new HttpPost(GOOGLE_TOKEN_ENDPOINT);
    List<NameValuePair> authArgs = new ArrayList<>();
    authArgs.add(new BasicNameValuePair("code", authCode));
    authArgs.add(new BasicNameValuePair("client_id", SecretsService.googleClientId));
    authArgs.add(new BasicNameValuePair("client_secret", SecretsService.googleClientSecret));
    authArgs.add(new BasicNameValuePair("redirect_uri", OAUTH_CALLBACK_URL));
    authArgs.add(new BasicNameValuePair("grant_type", "authorization_code"));
    UrlEncodedFormEntity tokenRequestEntity = new UrlEncodedFormEntity(authArgs, Consts.UTF_8);
    tokenPost.setEntity(tokenRequestEntity);

    try (CloseableHttpResponse response = AuthService.httpClient.execute(tokenPost)) {
        StatusLine statusLine = response.getStatusLine();
        int statusCode = statusLine.getStatusCode();
        if (statusCode != 200) {
            String loginStatus = "Login failed, google called us back with state token " + clientState;
            loginStatus += "and auth code " + authCode;
            loginStatus += ", but then we made a token request and got: "
                    + response.getStatusLine().getReasonPhrase() + "/"
                    + response.getStatusLine().getStatusCode();
            res.status(500);
            res.body(loginStatus);
            return INTERNAL_SERVER_ERROR.toString();
        }
        String authJson = EntityUtils.toString(response.getEntity());
        /**
         * What google returns (as of 01/05/2014)
         * https://developers.google.com/accounts/docs/OAuth2Login
         * { "access_token" : "ya29.lQAIu_8j0WfvQrOT3ZCExMddengITNLFoBsioB63QN1zNiLMvcQ7wslG",
         *   "token_type" : "Bearer",
         *   "expires_in" : 3597,
         *   "id_token" : "eyJhbGciOiJSUzI1NiIsImtpZCI6IjljNjMxNDFjMzAzNjkyY2E3Y2Q4MDAxZTUxNmNhNDVhZDdlNTJiZTIifQ.eyJpc3MiOiJhY2NvdW50cy5nb29nbGUuY29tIiwic3ViIjoiMTEwODMxNjM0MzU1MjI2MzY0OTQwIiwiYXpwIjoiNzI2ODM3ODY1MzU3LXRxczIwdTZsdXFjOW9hdjFicDN2YjhuZGdhdmpucmtmLmFwcHMuZ29vZ2xldXNlcmNvbnRlbnQuY29tIiwiZW1haWwiOiJzdHUyNmNvZGVAZ21haWwuY29tIiwiYXRfaGFzaCI6Im12WnMzaXgtR2NHSVVETThuTW9TaWciLCJlbWFpbF92ZXJpZmllZCI6dHJ1ZSwiYXVkIjoiNzI2ODM3ODY1MzU3LXRxczIwdTZsdXFjOW9hdjFicDN2YjhuZGdhdmpucmtmLmFwcHMuZ29vZ2xldXNlcmNvbnRlbnQuY29tIiwiaWF0IjoxNDEyNTM3NjE0LCJleHAiOjE0MTI1NDE1MTR9.Zc6zsQPkj5an-1XFJLCdOvMDw_rDAqIe3YzA8g2DzhbGqBbd6XiqjxeRl3XDfC1aqp0Vx15fGn5R1e9RIh8Nmp6xWPvCHrA0c4eY8SaIazJ6FBQyK-n3k1sxQNJpuYhVtctAKsmlxFZbilwL2OTqIf0RDx0BpcIgmnk_7gupGxs"
         * }
         *
         * TODO: parse JWT for token and store in DB ?
         *       or just do it in JS? JS will need to confirm anyways..
         */
        JsonParser jsonParser = new JsonParser();
        JsonElement authInfo = jsonParser.parse(authJson);
        JsonObject authObject = authInfo.getAsJsonObject();
        String accessToken = authObject.get(ACCESS_TOKEN_FIELD).getAsString();
        String accessExpires = authObject.get(TOKEN_EXPIRY_FIELD).getAsString();
        String accessId = authObject.get(ID_TOKEN_FIELD).getAsString();
        String loggedInEndpoint = OAUTH_REDIRECT_LOCATION + "?client_state=" + clientState + "&"
                + ACCESS_TOKEN_FIELD + "=" + accessToken + "&" + TOKEN_EXPIRY_FIELD + "=" + accessExpires + ""
                + "&" + ID_TOKEN_FIELD + "=" + accessId;
        /**
         * ID token is a jws signed object.. we should verify this in the servlet, since we can't verify the client state "secret"
         * Note that this secret is not the same secret used in the jws
         */
        res.redirect(URI.create(loggedInEndpoint).toString(), 303);
        res.body(authJson);
        return SEE_OTHER.toString();
    } catch (Exception e) {
        res.body(e.getMessage());
        res.status(500);
        return INTERNAL_SERVER_ERROR.toString();
    }
}

From source file:kendzi.kendzi3d.service.viewer.service.OverpassService.java

/**
 * Run given query on overpass server./*from   w  ww.ja v  a  2  s .  c o m*/
 * 
 * @param query
 *            query
 * @param encoding
 *            query encoding
 * @return response body
 */
public String findQuery(String query, String encoding) {

    HttpClient client = HttpClientBuilder.create().build();

    try {

        HttpPost post = new HttpPost(overpassUrl);

        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
        nameValuePairs.add(new BasicNameValuePair("data", query));

        post.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8"));

        HttpResponse response = client.execute(post);

        if (response == null) {
            throw new RuntimeException();
        }

        int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode != HttpStatus.SC_OK) {
            throw new IllegalStateException("overpass service returned error status: " + statusCode);
        }
        return EntityUtils.toString(response.getEntity(), "UTF-8");

    } catch (IOException e) {
        throw new IllegalStateException("error findQuery", e);
    }
}

From source file:ua.at.tsvetkov.data_processor.requests.PostRequest.java

@Override
public InputStream getInputStream() throws IOException {
    if (!isBuild()) {
        throw new IllegalArgumentException(REQUEST_IS_NOT_BUILDED);
    }/* w  w w  . j av a  2  s . c  o  m*/
    startTime = System.currentTimeMillis();

    HttpConnectionParams.setConnectionTimeout(httpParameters, configuration.getTimeout());
    HttpConnectionParams.setSoTimeout(httpParameters, configuration.getTimeout());

    HttpPost httpPost = new HttpPost(toString());
    httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs, encoding));
    httpPost.setParams(httpParameters);
    if (header != null) {
        httpPost.addHeader(header);
    }

    printToLogUrl();
    printToLogPairs();

    return getResponce(httpPost);
}

From source file:net.tirasa.olingooauth2.AzureADOAuth2HttpClientFactory.java

private void fetchAccessToken(final DefaultHttpClient httpClient, final List<BasicNameValuePair> data) {
    token = null;//from  w w  w. java2 s .com

    InputStream tokenResponse = null;
    try {
        final HttpPost post = new HttpPost(oauth2TokenServiceURI);
        post.setEntity(new UrlEncodedFormEntity(data, "UTF-8"));

        final HttpResponse response = httpClient.execute(post);

        tokenResponse = response.getEntity().getContent();
        token = (ObjectNode) new ObjectMapper().readTree(tokenResponse);
    } catch (Exception e) {
        throw new OAuth2Exception(e);
    } finally {
        IOUtils.closeQuietly(tokenResponse);
    }
}

From source file:securitytools.nessus.http.request.LoginRequest.java

/**
 * //from w  w  w.  j a  v  a  2s .  co m
 * @param username The user's Nessus username.
 * @param password The user's Nessus password.
 * @param sequenceId A unique number that will be echoed back to identify
 * this response.
 */
public LoginRequest(String username, String password, long sequenceId) {
    super("/login");

    if (ValidationUtils.isNullOrEmpty(username)) {
        throw new IllegalArgumentException("\"username\" argument cannot be null or empty.");
    }
    if (password == null) {
        throw new IllegalArgumentException("\"password\" argument cannot be null.");
    }
    if (ValidationUtils.isNegative(sequenceId)) {
        throw new IllegalArgumentException("\"sequenceId\" argument cannot be less than zero.");
    }

    List<NameValuePair> formparams = new ArrayList<NameValuePair>();
    formparams.add(new BasicNameValuePair("login", username));
    formparams.add(new BasicNameValuePair("password", password));
    formparams.add(new BasicNameValuePair("seq", String.valueOf(sequenceId)));

    setEntity(new UrlEncodedFormEntity(formparams, Consts.UTF_8));
}

From source file:securitytools.veracode.http.request.BeginScanRequest.java

public BeginScanRequest(String applicationId, String[] modules, String sandboxId) {
    super("/api/4.0/beginscan.do");

    if (applicationId == null) {
        throw new IllegalArgumentException("Application id cannot be null.");
    }// www .java 2 s  . co  m

    List<NameValuePair> formparams = new ArrayList<NameValuePair>();
    formparams.add(new BasicNameValuePair("app_id", applicationId));

    if (modules == null || modules.length == 0) {
        formparams.add(new BasicNameValuePair("scan_all_top_level_modules", "true"));
    } else {
        // Construct comma-separated list of module ids
        StringBuilder sb = new StringBuilder();
        for (String module : modules) {
            sb.append(module);
            sb.append(",");
        }
        formparams.add(new BasicNameValuePair("modules", sb.substring(0, sb.length() - 1)));
    }

    if (sandboxId != null) {
        formparams.add(new BasicNameValuePair("sandbox_id", sandboxId));
    }

    setEntity(new UrlEncodedFormEntity(formparams, Consts.UTF_8));
}