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:org.jenkinsci.plugins.fabric8.support.HubotClient.java

public static String notify(TaskListener listener, String room, String message) throws java.io.IOException {
    log(listener, "Hubot sending to room " + room + " => " + message);
    if (Strings.isNullOrBlank(room)) {
        log(listener, "you must specify a room!");
        return null;
    }//from   w w w . j a va 2  s . c  om
    if (Strings.isNullOrBlank(message)) {
        log(listener, "you must specify a message!");
        return null;
    }
    HttpHost host = RestClient.getHttpHost(listener, "hubot");
    if (host != null) {
        String roomWithSlugPrefix = room;
        if (roomWithSlugPrefix.startsWith("#")) {
            roomWithSlugPrefix = roomWithSlugPrefix.substring(1);
        }
        if (!roomWithSlugPrefix.startsWith(ROOM_SLUG_PREFIX)) {
            roomWithSlugPrefix = ROOM_SLUG_PREFIX + roomWithSlugPrefix;
        }
        HttpPost post = new HttpPost("/hubot/notify/" + roomWithSlugPrefix);
        log(listener, "Posting to " + host.toString() + " url: " + post.getURI());

        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
        nameValuePairs.add(new BasicNameValuePair("message", message));
        post.setEntity(new UrlEncodedFormEntity(nameValuePairs));

        CloseableHttpResponse response = RestClient.executeRequest(host, post);
        String result = RestClient.parse(response);
        log(listener, "Result: " + result);
        return result;
    } else {
        log(listener, "No service found!");
        return null;
    }
}

From source file:com.moongene.android.HttpService.java

private ServiceResult postHttpRequest(String endpointUrl, List<NameValuePair> nameValueList) {
    ServiceResult res = ServiceResult.FAILED_ABANDON;
    HttpClient httpClient = new DefaultHttpClient();
    HttpPost httpPost = new HttpPost(endpointUrl);

    try {/*from   w w w. jav a 2s.  co  m*/
        httpPost.setEntity(new UrlEncodedFormEntity(nameValueList));
        HttpEntity entity = httpClient.execute(httpPost).getEntity();

        if (entity != null) {
            String result = streamToString(entity.getContent());
            if (result.equals("1\n")) {
                res = ServiceResult.OK;
            }
        }
    } catch (IOException e) {
        Log.i(LOGTAG, "Can't post data to MoonGene Server, worth trying again. ", e);
        res = ServiceResult.FAILED_RETRY;
    } catch (OutOfMemoryError e) {
        Log.e(LOGTAG, "Can't post data to MoonGene Server, OutOfMemory. Abandoning.", e);
        res = ServiceResult.FAILED_ABANDON;
    }

    return res;
}

From source file:com.survivingwithandroid.jsontutorial.HttpClient.java

public String postJsonData(String data) {

    try {/*w  ww.  jav  a  2 s  .c om*/
        StringBuffer buffer = new StringBuffer();
        // Apache HTTP Reqeust
        System.out.println("Sending data..");
        System.out.println("Data: [" + data + "]");
        org.apache.http.client.HttpClient client = new DefaultHttpClient();
        HttpPost post = new HttpPost(URL);
        List<NameValuePair> nvList = new ArrayList<NameValuePair>();
        BasicNameValuePair bnvp = new BasicNameValuePair("json", data);
        // We can add more
        nvList.add(bnvp);
        post.setEntity(new UrlEncodedFormEntity(nvList));

        HttpResponse resp = client.execute(post);
        // We read the response
        InputStream is = resp.getEntity().getContent();
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder str = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            str.append(line + "\n");
        }
        is.close();
        buffer.append(str.toString());
        // Done!

        return buffer.toString();
    } catch (Throwable t) {
        t.printStackTrace();
    }

    return null;
}

From source file:ar.edu.ubp.das.src.chat.actions.ValidAction.java

@Override
public ForwardConfig execute(ActionMapping mapping, DynaActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws SQLException, RuntimeException {
    try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) {
        HttpPost httpPost = new HttpPost("http://25.136.78.82:8080/login/");
        List<NameValuePair> params = new ArrayList<>();
        params.add(new BasicNameValuePair("nombre_usuario", form.getItem("user")));
        params.add(new BasicNameValuePair("password", form.getItem("pw")));
        httpPost.setEntity(new UrlEncodedFormEntity(params));
        CloseableHttpResponse postResponse = httpClient.execute(httpPost);

        HttpEntity responseEntity = postResponse.getEntity();
        StatusLine responseStatus = postResponse.getStatusLine();
        String restResp = EntityUtils.toString(responseEntity);

        if (responseStatus.getStatusCode() != 200) {
            System.out.println(restResp);
            throw new RuntimeException("Los datos ingresados son incorrectos");
        }/*w w w  .java  2 s.co  m*/

        Header authHeader = postResponse.getFirstHeader("Auth-Token");
        String headerValue = authHeader != null ? authHeader.getValue() : "";

        HttpPost adminPost = new HttpPost("http://25.136.78.82:8080/login/admin");
        adminPost.addHeader("Authorization", "BEARER " + headerValue);
        adminPost.addHeader("accept", "application/json");

        postResponse = httpClient.execute(adminPost);
        responseEntity = postResponse.getEntity();
        responseStatus = postResponse.getStatusLine();

        if (responseStatus.getStatusCode() != 200) {
            throw new RuntimeException("Accesso restringido a Administradores");
        }

        request.getSession().setAttribute("user", restResp);
        request.getSession().setAttribute("token", headerValue);
        request.getSession().setAttribute("login_tmst", String.valueOf(System.currentTimeMillis()));

        return mapping.getForwardByName("success");

    } catch (IOException | RuntimeException e) {
        request.setAttribute("message", "Error al realizar login: " + e.getMessage());
        response.setStatus(401);
        return mapping.getForwardByName("failure");
    }
}

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

public HttpUriRequest getCall(String url) {
    try {//  w  w w .  jav  a 2  s.  c om

        HttpPost httpPost = new HttpPost(url);
        httpPost.setEntity(new UrlEncodedFormEntity(webData));
        return httpPost;
    } catch (Exception e) {
    }
    return null;
}

From source file:com.TaxiDriver.jy.DriverQuery.java

public static String getETA(String url, String fromLat, String fromLongi, String toLat, String toLongi,
        String type) {/*from ww  w.j av a 2  s  . co m*/

    HttpPost postJob = new HttpPost(HttpHelper.domain + "getduration.php");

    HttpParams httpParameters = new BasicHttpParams();
    // Set the timeout in milliseconds until a connection is established.
    // The default value is zero, that means the timeout is not used.
    int timeoutConnection = 3000;
    HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
    // Set the default socket timeout (SO_TIMEOUT)
    // in milliseconds which is the timeout for waiting for data.
    int timeoutSocket = 4900;
    HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
    DefaultHttpClient clientJob = new DefaultHttpClient(httpParameters);

    try {
        List<NameValuePair> infoJob = new ArrayList<NameValuePair>(2);
        infoJob.add(new BasicNameValuePair("url", url));

        infoJob.add(new BasicNameValuePair("fromLongi", fromLongi));
        infoJob.add(new BasicNameValuePair("fromLat", fromLat));
        infoJob.add(new BasicNameValuePair("toLongi", toLongi));
        infoJob.add(new BasicNameValuePair("toLat", toLat));
        infoJob.add(new BasicNameValuePair("type", type));

        postJob.setEntity(new UrlEncodedFormEntity(infoJob));

        HttpResponse response = clientJob.execute(postJob);

        String jsonString = HttpHelper.request(response);
        String duration = jsonString.trim();

        return duration;

    } catch (Exception ex) {
        return null;
    }

}

From source file:core.HttpClient.java

/**
 * Checks if we have the latest version/* w w  w  . j  a  va 2s .  co m*/
 * 
 * @param version
 * @return boolean - true if version is not up to date
 */
public static boolean isUpdateRequired(String version) {
    DefaultHttpClient httpclient = new DefaultHttpClient();
    try {
        HttpResponse response;
        HttpEntity entity;

        HttpPost httpost = new HttpPost(COMPANY_WEBSITE);
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair("version", version));
        httpost.setEntity(new UrlEncodedFormEntity(nvps));
        response = httpclient.execute(httpost);

        entity = response.getEntity();
        String data = "", line;
        BufferedReader br = new BufferedReader(new InputStreamReader(entity.getContent()));
        while ((line = br.readLine()) != null) {
            data += line;
        }

        if (data.startsWith("true")) {
            return true;
        } else {
            return false;
        }
    } catch (ClientProtocolException e) {
        e.printStackTrace();
        return false;
    } catch (IOException e) {
        e.printStackTrace();
        return false;
    } finally {
        httpclient.getConnectionManager().shutdown();
    }
}

From source file:org.sead.repositories.reference.util.SEADAuthenticator.java

static public HttpClientContext authenticate(String server) {

    boolean authenticated = false;
    log.info("Authenticating");

    String accessToken = SEADGoogleLogin.getAccessToken();

    // Now login to server and create a session
    CloseableHttpClient httpclient = HttpClients.createDefault();
    try {/*from  w  ww. j av a 2 s. co  m*/
        // //DoLogin is the auth endpoint when using the AUthFilter, versus
        // the api/authenticate endpoint when connecting to the ACR directly
        HttpPost seadAuthenticate = new HttpPost(server + "/DoLogin");
        List<NameValuePair> nvpList = new ArrayList<NameValuePair>(1);
        nvpList.add(0, new BasicNameValuePair("googleAccessToken", accessToken));

        seadAuthenticate.setEntity(new UrlEncodedFormEntity(nvpList));

        CloseableHttpResponse response = httpclient.execute(seadAuthenticate, localContext);
        try {
            if (response.getStatusLine().getStatusCode() == 200) {
                HttpEntity resEntity = response.getEntity();
                if (resEntity != null) {
                    // String seadSessionId =
                    // EntityUtils.toString(resEntity);
                    authenticated = true;
                }
            } else {
                // Seems to occur when google device id is not set on server
                // - with a Not Found response...
                log.error("Error response from " + server + " : " + response.getStatusLine().getReasonPhrase());
            }
        } finally {
            response.close();
            httpclient.close();
        }
    } catch (IOException e) {
        log.error("Cannot read sead-google.json");
        log.error(e.getMessage());
    }

    // localContext should have the cookie with the SEAD session key, which
    // nominally is all that's needed.
    // FixMe: If there is no activity for more than 15 minutes, the session
    // may expire, in which case,
    // re-authentication using the refresh token to get a new google token
    // to allow SEAD login again may be required

    // also need to watch the 60 minutes google token timeout - project
    // spaces will invalidate the session at 60 minutes even if there is
    // activity
    authTime = System.currentTimeMillis();

    if (authenticated) {
        return localContext;
    }
    return null;
}

From source file:com.aware.utils.Http.java

/**
 * Make a POST to the URL, with the ArrayList<NameValuePair> data
 * @param url//from ww  w.  j a  v a2s.  c  om
 * @param data
 * @return HttpEntity with server response. Use EntityUtils to extract values or object
 */
public HttpResponse dataPOST(String url, ArrayList<NameValuePair> data) {
    try {
        HttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);
        httpPost.setEntity(new UrlEncodedFormEntity(data));
        HttpResponse httpResponse = httpClient.execute(httpPost);

        int statusCode = httpResponse.getStatusLine().getStatusCode();
        if (statusCode != 200) {
            if (Aware.DEBUG) {
                Log.d(TAG, "Status: " + statusCode);
                Log.e(TAG, "URL:" + url);
                Log.e(TAG, EntityUtils.toString(httpResponse.getEntity()));
            }
        }
        return httpResponse;
    } catch (UnsupportedEncodingException e) {
        Log.e(TAG, e.getMessage());
        return null;
    } catch (ClientProtocolException e) {
        Log.e(TAG, e.getMessage());
        return null;
    } catch (IOException e) {
        Log.e(TAG, e.getMessage());
        return null;
    } catch (IllegalStateException e) {
        Log.e(TAG, e.getMessage());
        return null;
    }
}

From source file:com.quietlycoding.android.reader.util.api.Authentication.java

/**
 * This method returns back to the caller a proper authentication token to
 * use with the other API calls to Google Reader.
 * //from   ww  w  .j  av a2 s . c  o m
 * @param user
 *            - the Google username
 * @param pass
 *            - the Google password
 * @return sid - the returned authentication token for use with the API.
 * 
 */
public static String getAuthToken(String user, String pass) {
    final NameValuePair username = new BasicNameValuePair("Email", user);
    final NameValuePair password = new BasicNameValuePair("Passwd", pass);
    final NameValuePair service = new BasicNameValuePair("service", "reader");
    final List<NameValuePair> pairs = new ArrayList<NameValuePair>();
    pairs.add(username);
    pairs.add(password);
    pairs.add(service);

    try {
        final DefaultHttpClient client = new DefaultHttpClient();
        final HttpPost post = new HttpPost(AUTH_URL);
        final UrlEncodedFormEntity entity = new UrlEncodedFormEntity(pairs);

        post.setEntity(entity);

        final HttpResponse response = client.execute(post);
        final HttpEntity respEntity = response.getEntity();

        Log.d(TAG, "Server Response: " + response.getStatusLine());

        final InputStream in = respEntity.getContent();
        final BufferedReader reader = new BufferedReader(new InputStreamReader(in));
        String line = null;
        String result = null;

        while ((line = reader.readLine()) != null) {
            if (line.startsWith("SID")) {
                result = line.substring(line.indexOf("=") + 1);
            }
        }

        reader.close();
        client.getConnectionManager().shutdown();

        return result;
    } catch (final Exception e) {
        Log.d(TAG, "Exception caught:: " + e.toString());
        return null;
    }
}