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.wst.cls.HttpClientExample.java

private void sendPost() throws Exception {

    String url = "https://mestest.azurewebsites.net/EFFICIENCY_REPORT/Wip_Info_Active.aspx?PROVIDER_ID=1";

    HttpClient client = new DefaultHttpClient();
    HttpPost post = new HttpPost(url);

    // add header
    post.setHeader("User-Agent", USER_AGENT);

    List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
    urlParameters.add(new BasicNameValuePair("cboWerks", "ATMU-System"));
    urlParameters.add(new BasicNameValuePair("cboUnit", ""));
    urlParameters.add(new BasicNameValuePair("txtItemNo", ""));
    urlParameters.add(new BasicNameValuePair("txtDeptday", "10"));

    post.setEntity(new UrlEncodedFormEntity(urlParameters));

    HttpResponse response = client.execute(post);
    System.out.println("\nSending 'POST' request to URL : " + url);
    System.out.println("Post parameters : " + post.getEntity());
    System.out.println("Response Code : " + response.getStatusLine().getStatusCode());
    Thread.sleep(3000);//  w w  w.j a v  a 2  s. c  o m
    BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

    StringBuffer result = new StringBuffer();
    String line = "";
    while ((line = rd.readLine()) != null) {
        result.append(line);
        result.append("\n");
    }

    System.out.println(result.toString());

}

From source file:de.itomig.itopenterprise.GetItopJSON.java

/**
 * request data from itop server in json format - must be called from AsyncTask
 *
 * @param operation core/get etc/*from   w  w  w .  j  a  v a  2s. com*/
 * @param itopClass CI class
 * @param key  itop SELECT expression
 * @param output_fields attribute fields which should be returned
 * @return String with json data from server
 */
public static String postJsonToItopServer(String operation, String itopClass, String key,
        String output_fields) {
    AndroidHttpClient client = AndroidHttpClient.newInstance("Android");
    String result = "";

    try {
        HttpPost request = new HttpPost();
        String url = ItopConfig.getItopUrl();

        String req = url + "/webservices/rest.php?version=1.0";
        if (debug)
            Log.i(TAG, "json request=" + req);
        request.setURI(new URI(req));

        ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
        postParameters.add(ItopConfig.getItopUserNameValuePair());
        postParameters.add(ItopConfig.getItopPwdNameValuePair());

        JSONObject jsd = new JSONObject();
        jsd.put("operation", operation);
        jsd.put("class", itopClass);
        jsd.put("key", key);
        jsd.put("output_fields", output_fields);

        postParameters.add(new BasicNameValuePair("json_data", jsd.toString()));
        UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(postParameters);
        request.setEntity(formEntity);

        // request.addHeader(HTTP.CONTENT_TYPE, "application/json");
        HttpResponse response = client.execute(request);
        String status = response.getStatusLine().toString();
        if (debug)
            Log.i(TAG, "status: " + status);

        if (status.contains("200") && status.contains("OK")) {

            // request worked fine, retrieved some data
            InputStream instream = response.getEntity().getContent();
            result = convertStreamToString(instream);
            //Log.d(TAG, "result is: " + result);
        } else // some error in http response
        {
            Log.e(TAG, "Get data - http-ERROR: " + status);
            result = "SERVER_ERROR: http status " + status;
        }

    } catch (Exception e) {
        // Toast does not work in background task
        Log.e(TAG, "Get data -  " + e.toString());
        result = "SERVER_ERROR: " + e.toString();
    } finally {
        client.close(); // needs to be done for androidhttpclient
        if (debug)
            Log.i(TAG, "...finally.. get data finished");
    }
    return result;

}

From source file:de.chaosdorf.meteroid.longrunningio.LongRunningIOPost.java

@Override
protected String doInBackground(Void... params) {
    HttpClient httpClient = new DefaultHttpClient();
    HttpContext localContext = new BasicHttpContext();
    HttpPost httpPost = new HttpPost(url);
    try {/*from w ww .  j  a  v a  2  s .c  om*/
        httpPost.setEntity(new UrlEncodedFormEntity(postData));
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
        return null;
    }
    try {
        HttpResponse response = httpClient.execute(httpPost, localContext);
        int code = response.getStatusLine().getStatusCode();
        if (code >= 400 && code <= 599) {
            callback.displayErrorMessage(id, response.getStatusLine().getReasonPhrase());
            return null;
        }
        HttpEntity entity = response.getEntity();
        return EntityUtils.toString(entity, HTTP.UTF_8);
    } catch (Exception e) {
        callback.displayErrorMessage(id, e.getLocalizedMessage());
        return null;
    }
}

From source file:cf.client.DefaultUaa.java

@Override
public Token getClientToken(String client, String clientSecret) {
    try {/*from  w ww  .  j a va 2 s  . c om*/
        final HttpPost post = new HttpPost(uaa.resolve(OAUTH_TOKEN_URI));

        post.setHeader(ACCEPT_JSON);

        post.setHeader(createClientCredentialsHeader(client, clientSecret));

        // TODO Do we need to make the grant type configurable?
        final BasicNameValuePair nameValuePair = new BasicNameValuePair("grant_type", "client_credentials");
        post.setEntity(new UrlEncodedFormEntity(Arrays.asList(nameValuePair)));

        final HttpResponse response = httpClient.execute(post);
        try {
            validateResponse(response);
            final HttpEntity entity = response.getEntity();
            final InputStream content = entity.getContent();
            return Token.parseJson(content);
        } finally {
            HttpClientUtils.closeQuietly(response);
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.gmail.at.faint545.tasks.HistoryActionTask.java

@Override
protected String doInBackground(String... params) {
    HttpClient httpClient = new DefaultHttpClient();
    HttpPost httpRequest = new HttpPost(url);
    ArrayList<NameValuePair> arguments = new ArrayList<NameValuePair>();
    arguments.add(new BasicNameValuePair(SabnzbdConstants.APIKEY, api));
    arguments.add(new BasicNameValuePair(SabnzbdConstants.OUTPUT, SabnzbdConstants.OUTPUT_JSON));

    switch (request) {
    case DELETE:/*from  w w w  . ja  va 2s  .  c o  m*/
        prepareForDelete(arguments, params);
        break;
    case RETRY:
        prepareForRetry(arguments, params);
        break;
    }

    try {
        httpRequest.setEntity(new UrlEncodedFormEntity(arguments));
        HttpResponse result = httpClient.execute(httpRequest);
        InputStream inStream = result.getEntity().getContent();
        BufferedReader br = new BufferedReader(new InputStreamReader(inStream), 8);
        StringBuilder jsonStringBuilder = new StringBuilder();
        String line;
        while ((line = br.readLine()) != null) {
            if (line.length() > 0)
                jsonStringBuilder.append(line);
        }
        br.close();
        inStream.close();
        return jsonStringBuilder.toString();
    } catch (ClientProtocolException e) {
        return ClientProtocolException.class.getName();
    } catch (IOException e) {
        return IOException.class.getName();
    }
}

From source file:org.wso2.identity.integration.test.user.mgt.UserMgtUISecurityTestCase.java

/**
 * Tests the open redirect vulnerability in change-passwd-finish.jsp.
 * @throws IOException//from   w  w  w  . j  a va2  s .  c  o m
 */
@Test(alwaysRun = true, description = "Testing open redirect vulnerability")
public void openRedirectTest() throws IOException {

    HttpClient httpClient = new DefaultHttpClient();

    HttpPost loginPost = new HttpPost(SERVER_URL + LOGIN_PAGE_CONTEXT);

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

    loginParameters.add(new BasicNameValuePair("username", USER_NAME));
    loginParameters.add(new BasicNameValuePair("password", OLD_PASSWORD));

    loginPost.setEntity(new UrlEncodedFormEntity(loginParameters));

    HttpResponse loginResponse = httpClient.execute(loginPost);
    String cookie = loginResponse.getHeaders("Set-Cookie")[0].getValue();

    EntityUtils.consume(loginResponse.getEntity());

    HttpPost post = new HttpPost(SERVER_URL + CHANGE_PASSWORD_CONTEXT);

    post.setHeader("Cookie", cookie);

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

    urlParameters.add(new BasicNameValuePair("pwd_regex", PW_REGEX));
    urlParameters.add(new BasicNameValuePair("username", USER_NAME));
    urlParameters.add(new BasicNameValuePair("isUserChange", "true"));
    urlParameters.add(new BasicNameValuePair("returnPath", RETURN_PATH));
    urlParameters.add(new BasicNameValuePair("currentPassword", NEW_PASSWORD));
    urlParameters.add(new BasicNameValuePair("checkPassword", OLD_PASSWORD));

    post.setEntity(new UrlEncodedFormEntity(urlParameters));

    HttpResponse response = httpClient.execute(post);

    String repString = EntityUtils.toString(response.getEntity());

    if (repString != null) {
        Assert.assertFalse(repString.contains(RETURN_PATH), "Possible open redirect vulnerability.");
    } else {
        Assert.assertTrue(false, "Invalid response for password update.");
    }

}

From source file:net.alchemiestick.katana.winehqappdb.Metrics.java

@Override
protected StringBuffer doInBackground(HttpPost... url) {
    setNamedData("lic", "2");
    setNamedData("googleAcc", getAcc());
    HttpPost httpPost = url[0];//from   w  w w  .  j  ava  2s  . c o m
    try {
        httpPost.setEntity(new UrlEncodedFormEntity(webData));
    } catch (Exception e) {
    }
    StringBuffer sb = new StringBuffer("");
    HttpResponse res = null;
    while (res == null)
        try {
            SearchView.do_sleep(500);
            res = httpClient.execute(httpPost);
        } finally {
            continue;
        }

    while (res.getStatusLine() == null)
        SearchView.do_sleep(500);

    try {
        BufferedReader br = new BufferedReader(new InputStreamReader(res.getEntity().getContent()), 4096);
        String line;
        String NL = System.getProperty("line.seperator");
        while ((line = br.readLine()) != null) {
            sb.append(line + NL);
        }
    } catch (Exception ex) {
    } finally {
        httpClient.close();
    }
    return sb;
}

From source file:org.forgerock.openam.mobile.commons.FormRestRequest.java

/**
 * Alters the request to insert additional HTTP POST x-www-form-urlencoded data
 *///from  ww w.  j a v  a  2s. c  om
public void insertData(HashMap<String, String> formParameters) {

    if (formParameters == null) {
        return;
    }

    HttpPost request = getRequest();

    try {
        List<NameValuePair> data = new ArrayList<NameValuePair>();

        for (String s : formParameters.keySet()) {
            NameValuePair nvp = new BasicNameValuePair(s, formParameters.get(s));
            data.add(nvp);
        }

        UrlEncodedFormEntity formData = new UrlEncodedFormEntity(data);

        formData.setContentType(CONTENT_TYPE);
        request.setEntity(formData);
    } catch (UnsupportedEncodingException e) {
        fail(TAG, "Unable to set entity.");
    }
}

From source file:com.crossword.activity.FeedbackActivity.java

public void postMessage() {
    // Create a new HttpClient and Post Header
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost(Crossword.MAIL_URL);
    try {//w w w  . j a  v  a  2 s . c  o  m
        EditText feedMessage = (EditText) findViewById(R.id.feed_message);

        // Add your data
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
        nameValuePairs.add(new BasicNameValuePair("from",
                android.os.Build.MODEL + " (" + android.os.Build.VERSION.RELEASE + ")"));
        nameValuePairs.add(new BasicNameValuePair("message", feedMessage.getText().toString()));
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

        // Execute HTTP Post Request
        HttpResponse response = httpclient.execute(httppost);
        if (response.getStatusLine().getStatusCode() == 200) {
            runOnUiThread(new Runnable() {
                public void run() {
                    Toast.makeText(FeedbackActivity.this, R.string.feedback_send_success, Toast.LENGTH_SHORT)
                            .show();
                }
            });
            finish();
            return;
        }

        String line;
        StringBuilder total = new StringBuilder();
        BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
        while ((line = rd.readLine()) != null) {
            total.append(line);
        }
        error = Html.fromHtml(total.toString()).toString();
    } catch (ClientProtocolException e) {
        error = getResources().getString(R.string.exception_network);
        e.printStackTrace();
    } catch (IOException e) {
        error = getResources().getString(R.string.exception_network);
        e.printStackTrace();
    }
}

From source file:android.hawkencompanionapp.asynctasks.ForgotPasswordTask.java

private void sendPasswordResetRequest(UserForgottenPassword userForgottenPasswords) {
    final HttpPost httpPost = new HttpPost(mResetUrl);
    final HttpClient httpClient = new DefaultHttpClient();
    final List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
    HttpResponse httpResponse;//from w ww  .j ava2 s. c  om

    try {
        nameValuePairs.add(new BasicNameValuePair("EmailAddress", userForgottenPasswords.getEmailAddress()));
        httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        httpResponse = httpClient.execute(httpPost);
        final String responseStr = EntityUtils.toString(httpResponse.getEntity());
        if (!responseStr.contains("404")) {
            userForgottenPasswords.setAccountValid(true);
        }
        Logger.debug(this, "Email address not found?: " + String.valueOf(mEmailAddressNotFound));
    } catch (IOException e) {
        Logger.error(this, e.getMessage());
    }
}