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:ADP.codeutils.HttpClientExample.java

public void sendPost() throws Exception {

    String url = "https://selfsolve.apple.com/wcResults.do";

    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("sn", "C02G8416DRJM"));
    urlParameters.add(new BasicNameValuePair("cn", ""));
    urlParameters.add(new BasicNameValuePair("locale", ""));
    urlParameters.add(new BasicNameValuePair("caller", ""));
    urlParameters.add(new BasicNameValuePair("num", "12345"));

    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());

    BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

    StringBuffer result = new StringBuffer();
    String line = "";
    while ((line = rd.readLine()) != null) {
        result.append(line);/*from  www. j  av a2  s .  c  om*/
    }

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

}

From source file:org.opencastproject.search.remote.SearchServiceRemoteImpl.java

/**
 * {@inheritDoc}//from  w  ww . j  av  a2s. com
 * 
 * @see org.opencastproject.search.api.SearchService#add(org.opencastproject.mediapackage.MediaPackage)
 */
@Override
public Job add(MediaPackage mediaPackage) throws SearchException {
    HttpPost post = new HttpPost("/add");
    try {
        List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
        params.add(new BasicNameValuePair("mediapackage", MediaPackageParser.getAsXml(mediaPackage)));
        post.setEntity(new UrlEncodedFormEntity(params));
    } catch (Exception e) {
        throw new SearchException("Unable to assemble a remote search request for mediapackage " + mediaPackage,
                e);
    }

    HttpResponse response = getResponse(post);
    try {
        if (response != null) {
            Job job = JobParser.parseJob(response.getEntity().getContent());
            logger.info("Publishing mediapackage '{}' using a remote search service",
                    mediaPackage.getIdentifier());
            return job;
        }
    } catch (Exception e) {
        throw new SearchException(
                "Unable to publish " + mediaPackage.getIdentifier() + " using a remote search service", e);
    } finally {
        closeConnection(response);
    }

    throw new SearchException(
            "Unable to publish " + mediaPackage.getIdentifier() + " using a remote search service");
}

From source file:org.fedoraproject.copr.client.impl.RpcCommand.java

public T execute(DefaultCoprSession session) throws CoprException {
    try {/*from w ww .  j  a  va  2  s. co m*/
        HttpClient client = session.getClient();

        String baseUrl = session.getConfiguration().getUrl();
        String commandUrl = getCommandUrl();
        String url = baseUrl + commandUrl;

        Map<String, String> extraArgs = getExtraArguments();
        HttpUriRequest request;
        if (extraArgs == null) {
            request = new HttpGet(url);
        } else {
            HttpPost post = new HttpPost(url);
            request = post;

            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
            for (Entry<String, String> entry : extraArgs.entrySet()) {
                nameValuePairs.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
            }
            post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        }

        if (requiresAuthentication()) {
            String login = session.getConfiguration().getLogin();
            if (login == null || login.isEmpty())
                throw new CoprException("Authentification is required to perform this command "
                        + "but no login was provided in configuration");

            String token = session.getConfiguration().getToken();
            if (token == null || token.isEmpty())
                throw new CoprException("Authentification is required to perform this command "
                        + "but no login was provided in configuration");

            String auth = login + ":" + token;
            String encodedAuth = DatatypeConverter.printBase64Binary(auth.getBytes(StandardCharsets.UTF_8));
            request.setHeader("Authorization", "Basic " + encodedAuth);
        }

        request.addHeader("Accept", APPLICATION_JSON.getMimeType());

        HttpResponse response = client.execute(request);
        int returnCode = response.getStatusLine().getStatusCode();

        if (returnCode != HttpURLConnection.HTTP_OK) {
            throw new CoprException(
                    "Copr RPC failed: HTTP " + returnCode + " " + response.getStatusLine().getReasonPhrase());
        }

        Reader responseReader = new InputStreamReader(response.getEntity().getContent());
        JsonParser parser = new JsonParser();
        JsonObject rpcResponse = parser.parse(responseReader).getAsJsonObject();

        String rpcStatus = rpcResponse.get("output").getAsString();
        if (!rpcStatus.equals("ok")) {
            throw new CoprException("Copr RPC returned failure reponse");
        }

        return parseResponse(rpcResponse);
    } catch (IOException e) {
        throw new CoprException("Failed to call remote Copr procedure", e);
    }
}

From source file:att.jaxrs.client.Content.java

public static String updateContent(Content content) {
    List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
    urlParameters.add(new BasicNameValuePair("content_id", content.getContent_id().toString()));
    urlParameters.add(new BasicNameValuePair("level", content.getLevel()));
    urlParameters.add(new BasicNameValuePair("presenter", content.getPresenter()));
    urlParameters.add(new BasicNameValuePair("reads", content.getReads()));

    String resultStr = "";

    try {//from   w w w . j a va2  s.com

        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost post = new HttpPost(Constants.UPDATE_CONTENT_RESOURCE);
        post.setEntity(new UrlEncodedFormEntity(urlParameters));
        HttpResponse result = httpClient.execute(post);
        System.out.println(Constants.RESPONSE_STATUS_CODE + result);
        resultStr = Util.getStringFromInputStream(result.getEntity().getContent());
        System.out.println(Constants.RESPONSE_BODY + resultStr);

    } catch (Exception e) {
        System.out.println(e.getMessage());

    }
    return resultStr;
}

From source file:com.radioreddit.android.api.PerformLogin.java

@Override
protected Boolean doInBackground(String... params) {
    final String username = params[0];
    final String password = params[1];

    if (username == null || password == null || username.isEmpty() || password.isEmpty()) {
        return false;
    }/*from  w ww.j  a v a2s.co  m*/

    // Prepare POST, execute it, parse response as JSON.
    JSONObject response;
    try {
        final HttpClient httpClient = new DefaultHttpClient();
        final HttpPost httpPost = new HttpPost("https://ssl.reddit.com/api/login");
        final List<NameValuePair> nameValuePairs = new ArrayList<>();
        nameValuePairs.add(new BasicNameValuePair("user", username));
        nameValuePairs.add(new BasicNameValuePair("passwd", password));
        nameValuePairs.add(new BasicNameValuePair("api_type", "json"));
        httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        httpPost.setHeader("User-Agent", RedditApi.USER_AGENT);
        final HttpResponse httpResponse = httpClient.execute(httpPost);
        final String responseBody = EntityUtils.toString(httpResponse.getEntity());
        if (MusicService.DEBUG) {
            Log.i(RedditApi.TAG, "Reddit API login response: " + responseBody);
        }
        response = new JSONObject(responseBody);
        response = response.getJSONObject("json");
    } catch (UnsupportedEncodingException e) {
        Log.i(RedditApi.TAG, "UnsupportedEncodingException while performing login", e);
        return false;
    } catch (ClientProtocolException e) {
        Log.i(RedditApi.TAG, "ClientProtocolException while performing login", e);
        return false;
    } catch (IOException e) {
        Log.i(RedditApi.TAG, "IOException while performing login", e);
        return false;
    } catch (ParseException e) {
        Log.i(RedditApi.TAG, "ParseException while performing login", e);
        return false;
    } catch (JSONException e) {
        Log.i(RedditApi.TAG, "JSONException while performing login", e);
        return false;
    }

    // Check for failure.
    if (response == null) {
        Log.i(RedditApi.TAG, "Response was null while performing login");
        return false;
    }

    // Check for errors.
    final JSONArray errors = response.optJSONArray("errors");
    if (errors == null || errors.length() > 0) {
        Log.i(RedditApi.TAG, "Response has errors while performing login");
        return false;
    }

    // Check for data.
    final JSONObject data = response.optJSONObject("data");
    if (data == null) {
        Log.i(RedditApi.TAG, "Response missing data while performing login");
        return false;
    }

    // Get modhash and cookie from data.
    mUser = username;
    mModhash = data.optString("modhash");
    mCookie = data.optString("cookie");
    if (mModhash.length() == 0 || mCookie.length() == 0) {
        Log.i(RedditApi.TAG, "Response missing modhash/cookie while performing login");
        return false;
    }

    return true;
}

From source file:org.opencastproject.remotetest.server.resource.IngestResources.java

public static HttpResponse ingest(TrustedHttpClient client, String mediaPackageId) throws Exception {
    HttpPost post = new HttpPost(getServiceUrl() + "ingest");
    List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
    params.add(new BasicNameValuePair("mediaPackage", mediaPackageId));
    post.setEntity(new UrlEncodedFormEntity(params));
    return client.execute(post);
}

From source file:ezbake.azkaban.manager.AuthenticationManager.java

/**
 * Logs into Azkaban and returns the result with the session ID
 *
 * @return {@link ezbake.azkaban.manager.result.AuthenticationResult} containing the session ID if successful
 *//*w  w  w .  j a  v a  2s. co  m*/
public AuthenticationResult login() {
    try {
        final List<NameValuePair> pairs = new ArrayList<>();
        pairs.add(new BasicNameValuePair("action", "login"));
        pairs.add(new BasicNameValuePair("username", username));
        pairs.add(new BasicNameValuePair("password", password));

        HttpPost post = new HttpPost(azkabanURI);
        post.setEntity(new UrlEncodedFormEntity(pairs));

        String json = HttpManager.post(post);
        return (AuthenticationResult) JsonUtil.deserialize(json, AuthenticationResult.class);
    } catch (Exception ex) {
        ex.printStackTrace();
        return new AuthenticationResult(ex.getMessage());
    }
}

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

private void getUserSession(UserLoginSession userLoginSession) {
    final HttpPost httpPost = new HttpPost(mLoginUrl);
    final List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
    final DefaultHttpClient httpClient = new DefaultHttpClient();
    HttpResponse httpResponse;/*from   ww w.  j  a  v  a 2  s .  c o  m*/

    try {
        Logger.debug(this, "Logging in user: " + userLoginSession.getEmailAddress());
        nameValuePairs.add(new BasicNameValuePair("EmailAddress", userLoginSession.getEmailAddress()));
        nameValuePairs.add(new BasicNameValuePair("Password", userLoginSession.getUserPassword()));
        httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        httpResponse = httpClient.execute(httpPost);

        if (isUserLoginValid(httpResponse)) {
            final List<Cookie> cookies = httpClient.getCookieStore().getCookies();
            Logger.debug(this, cookies.toString());
            userLoginSession.setUserSession(cookies);
            userLoginSession.setUserIsValid();
        }
    } catch (IOException e) {
        Logger.error(this, e.getMessage());
    }
}

From source file:org.kevinferrare.solarSystemDataRetriever.utils.HttpClientTool.java

/**
 * Sends an HTTP POST request with the given data to the given URL
 * /*from   w  w w.  j av  a 2 s  .c  om*/
 * @param url
 *            the url to send the request
 * @param nameValuePairs
 *            the list of parameters to send
 * @return the response to the request.
 * @throws UnsupportedEncodingException
 * @throws IOException
 * @throws ClientProtocolException
 */
public byte[] postData(String url, List<NameValuePair> nameValuePairs)
        throws UnsupportedEncodingException, IOException, ClientProtocolException {
    HttpPost httppost = new HttpPost(url);
    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
    return httpclient.execute(httppost, handler);
}

From source file:simple.crawler.ext.vanilla.VanillaForumUtil.java

public static HttpContext login(String loginURL, String username, String password) throws Exception {
    DefaultHttpClient httpclient = HttpClientFactory.getInstance();
    CookieStore cookieStore = new BasicCookieStore();
    HttpContext httpContext = new BasicHttpContext();
    httpContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
    HttpResponse res = httpclient.execute(new HttpGet(loginURL), httpContext);

    String html = HttpClientUtil.getContentBodyAsString(res);
    HtmlParser parser = new HtmlParser();
    Document doc = parser.parseNonWellForm(html);

    ///*from www .  j av a  2  s.  co m*/
    Node loginTransientKey = (Node) XPathUtil.read(doc, "//*[@id=\"Form_TransientKey\"]", XPathConstants.NODE);
    Node hpt = (Node) XPathUtil.read(doc, "//*[@id=\"Form_hpt\"]", XPathConstants.NODE);
    Node target = (Node) XPathUtil.read(doc, "//*[@id=\"Form_Target\"]", XPathConstants.NODE);
    Node clientHour = (Node) XPathUtil.read(doc, "//*[@id=\"Form_ClientHour\"]", XPathConstants.NODE);

    //
    List<NameValuePair> list = new ArrayList<NameValuePair>();
    list.add(new BasicNameValuePair("Form/TransientKey", ((Element) loginTransientKey).getAttribute("value")));
    list.add(new BasicNameValuePair("Form/hpt", ((Element) hpt).getAttribute("value")));
    list.add(new BasicNameValuePair("Form/Target", ((Element) target).getAttribute("value")));
    list.add(new BasicNameValuePair("Form/ClientHour", ((Element) clientHour).getAttribute("value")));
    list.add(new BasicNameValuePair("Form/Email", "admin"));
    list.add(new BasicNameValuePair("Form/Password", "admin"));
    list.add(new BasicNameValuePair("Form/Sign_In", "Sign In"));
    list.add(new BasicNameValuePair("Form/RememberMe", "1"));
    list.add(new BasicNameValuePair("Checkboxes[]", "RememberMe"));

    HttpPost post = new HttpPost(loginURL);
    post.setEntity(new UrlEncodedFormEntity(list));
    res = httpclient.execute(post, httpContext);
    return httpContext;
}