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:at.ac.tuwien.dsg.cloudlyra.utils.RestHttpClient.java

public void callPostMethod(List<NameValuePair> paramList) {

    try {//from   w  ww  .  j a  v a 2s . c o  m

        HttpPost post = new HttpPost(url);

        // add header
        post.setHeader("Host", "smartsoc.infosys.tuwien.ac.at");
        //post.setHeader("User-Agent", USER_AGENT);
        //post.setHeader("Connection", "keep-alive");
        post.setHeader("Content-Type", "application/x-www-form-urlencoded");

        // set content
        post.setEntity(new UrlEncodedFormEntity(paramList));

        logger.log(Level.INFO, "\nSending 'POST' request to URL : " + url);
        logger.log(Level.INFO, "Post parameters : " + paramList);
        System.out.println();

        HttpClient client = HttpClientBuilder.create().build();
        HttpResponse response = client.execute(post);

        int responseCode = response.getStatusLine().getStatusCode();

        logger.log(Level.INFO, "Response Code : " + responseCode);

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

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

        logger.log(Level.INFO, result.toString());

    } catch (Exception ex) {

    }

}

From source file:org.labkey.freezerpro.export.GetFreezerSamplesCommand.java

public FreezerProCommandResonse execute(HttpClient client, PipelineJob job) {
    HttpPost post = new HttpPost(_url);

    try {/* w  w w. j  a  v  a2s .  c o m*/
        List<NameValuePair> params = new ArrayList<NameValuePair>();

        params.add(new BasicNameValuePair("method", "freezer_samples"));
        params.add(new BasicNameValuePair("username", _username));
        params.add(new BasicNameValuePair("password", _password));
        params.add(new BasicNameValuePair("id", _typeId));
        params.add(new BasicNameValuePair("limit", "10000"));

        post.setEntity(new UrlEncodedFormEntity(params));

        ResponseHandler<String> handler = new BasicResponseHandler();

        HttpResponse response = client.execute(post);
        StatusLine status = response.getStatusLine();

        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK)
            return new GetFreezerSamplesResponse(_export, handler.handleResponse(response),
                    status.getStatusCode(), job);
        else
            return new GetFreezerSamplesResponse(_export, status.getReasonPhrase(), status.getStatusCode(),
                    job);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:org.megam.deccanplato.http.TransportMachinery.java

public static TransportResponse post(TransportTools nuts) throws ClientProtocolException, IOException {
    DefaultHttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost(nuts.urlString());
    System.out.println("NUTS" + nuts.toString());
    if (nuts.headers() != null) {
        for (Map.Entry<String, String> headerEntry : nuts.headers().entrySet()) {
            //this if condition is set for twilio Rest API to add credentials to DefaultHTTPClient, conditions met twilio work.
            if (headerEntry.getKey().equalsIgnoreCase("provider")
                    & headerEntry.getValue().equalsIgnoreCase(nuts.headers().get("provider"))) {
                httpclient.getCredentialsProvider().setCredentials(
                        new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT), new UsernamePasswordCredentials(
                                nuts.headers().get("account_sid"), nuts.headers().get("oauth_token")));
            }/*  www .jav  a 2 s. c om*/
            //this else part statements for other providers
            else {
                httppost.addHeader(headerEntry.getKey(), headerEntry.getValue());
            }
        }
    }
    if (nuts.fileEntity() != null) {
        httppost.setEntity(nuts.fileEntity());
    }
    if (nuts.pairs() != null && (nuts.contentType() == null)) {
        httppost.setEntity(new UrlEncodedFormEntity(nuts.pairs()));
    }

    if (nuts.contentType() != null) {
        httppost.setEntity(new StringEntity(nuts.contentString(), nuts.contentType()));
    }
    TransportResponse transportResp = null;
    System.out.println(httppost.toString());
    try {
        HttpResponse httpResp = httpclient.execute(httppost);
        transportResp = new TransportResponse(httpResp.getStatusLine(), httpResp.getEntity(),
                httpResp.getLocale());
    } finally {
        httppost.releaseConnection();
    }
    return transportResp;

}

From source file:com.victorkifer.AndroidTemplates.api.Downloader.java

private static HttpResponse makeHttpPostRequest(String url, List<NameValuePair> params) throws IOException {
    HttpPost httpPost = new HttpPost(url);

    if (params != null) {
        httpPost.setEntity(new UrlEncodedFormEntity(params));
    }//from w w  w  .j  a v a  2s.c o  m

    Logger.e(TAG, url);

    return httpClient.execute(httpPost);
}

From source file:cardgametrackercs319.DBConnectionManager.java

public static String getPlayerInfo(String playerID) throws UnsupportedEncodingException, IOException {
    HttpClient client = new DefaultHttpClient();
    HttpPost post = new HttpPost("http://ozymaxx.net/cs319/player_info.php");

    post.setHeader("User-Agent", USER_AGENT);
    ArrayList<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
    urlParameters.add(new BasicNameValuePair("pid", playerID));

    post.setEntity(new UrlEncodedFormEntity(urlParameters));

    HttpResponse response = client.execute(post);
    BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
    StringBuffer result = new StringBuffer();
    String resLine = "";

    while ((resLine = reader.readLine()) != null) {
        result.append(resLine);/*from   ww  w  .j  a v  a  2  s  .com*/
    }

    return result.toString();
}

From source file:com.example.mysqltest.ServiceHandler.java

public String makeServiceCall(String url, int method, List<NameValuePair> params) {
    try {/*from w  w w. j a v a2  s. co m*/

        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpEntity httpEntity = null;
        HttpResponse httpResponse = null;

        if (method == POST) {
            HttpPost httpPost = new HttpPost(url);

            if (params != null) {
                httpPost.setEntity(new UrlEncodedFormEntity(params));
            }

            httpResponse = httpClient.execute(httpPost);

        } else if (method == GET) {

            if (params != null) {
                String paramString = URLEncodedUtils.format(params, "utf-8");
                url += "?" + paramString;
            }
            HttpGet httpGet = new HttpGet(url);

            httpResponse = httpClient.execute(httpGet);

        }
        httpEntity = httpResponse.getEntity();
        is = httpEntity.getContent();

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        is.close();
        response = sb.toString();
    } catch (Exception e) {
        Log.e("Buffer Error", "Error: " + e.toString());
    }

    return response;
}

From source file:de.tudarmstadt.dvs.myhealthassistant.myhealthhub.commontools.JSONParser.java

public JSONObject makeHttpRequest(String url, String method, List<NameValuePair> params) {

    // Making HTTP request
    try {//ww w  . jav  a  2  s .  c  om

        // check for request method
        if (method == "POST") {
            // request method is POST
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);
            httpPost.setEntity(new UrlEncodedFormEntity(params));

            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();

        } else if (method == "GET") {
            // request method is GET
            DefaultHttpClient httpClient = new DefaultHttpClient();
            String paramString = URLEncodedUtils.format(params, "utf-8");
            url += "?" + paramString;
            HttpGet httpGet = new HttpGet(url);

            HttpResponse httpResponse = httpClient.execute(httpGet);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();
        }

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        is.close();
        json = sb.toString();
    } catch (Exception e) {
        Log.e("Buffer Error", "Error converting result " + e.toString());
    }

    // try parse the string to a JSON object
    try {
        jObj = new JSONObject(json);
    } catch (JSONException e) {
        Log.e("JSON Parser", "Error parsing data: " + e.toString());
        Log.e("JSON Parser", "Error parsing data; source: " + json);
    }

    // return JSON String
    return jObj;

}

From source file:guru.nidi.loader.url.FormLoginUrlFetcher.java

@Override
public InputStream fetchFromUrl(CloseableHttpClient client, String base, String name, long ifModifiedSince) {
    try {/*ww  w . java 2  s  .com*/
        final HttpPost login = new HttpPost(base + "/" + loginUrl);
        final List<NameValuePair> params = new ArrayList<>();
        params.add(new BasicNameValuePair(loginField, this.login));
        params.add(new BasicNameValuePair(passwordField, password));
        postProcessLoginParameters(params);
        login.setEntity(new UrlEncodedFormEntity(params));
        try (final CloseableHttpResponse getResult = client.execute(postProcessLogin(login))) {
            if (getResult.getStatusLine().getStatusCode() != HttpStatus.SC_MOVED_TEMPORARILY) {
                throw new Loader.ResourceNotFoundException(name,
                        "Could not login: " + getResult.getStatusLine().toString());
            }
            EntityUtils.consume(getResult.getEntity());
        }
        return super.fetchFromUrl(client, base + "/" + loadPath, name, ifModifiedSince);
    } catch (IOException e) {
        throw new Loader.ResourceNotFoundException(name, e);
    }
}

From source file:ru.elifantiev.yandex.YandexAPIService.java

protected JSONObject callMethod(String methodName, Map<String, String> params) {

    Uri.Builder builder = getServiceUri().buildUpon();
    builder.scheme("https").appendPath("api").appendPath(methodName);

    HttpClient client = SSLHttpClientFactory.getNewHttpClient();
    HttpPost method = new HttpPost(builder.build().toString());

    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(params.size());
    for (String param : params.keySet()) {
        nameValuePairs.add(new BasicNameValuePair(param, params.get(param)));
    }/*from www .  j ava 2  s .co m*/
    try {
        method.setEntity(new UrlEncodedFormEntity(nameValuePairs));
    } catch (UnsupportedEncodingException e) {
        throw new MethodCallException("Call to " + methodName + " failed", e);
    }

    method.setHeader(new BasicHeader("Authorization", "Bearer " + token.toString()));

    try {
        HttpResponse response = client.execute(method);
        int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode == 200) {
            return (JSONObject) new JSONTokener(EntityUtils.toString(response.getEntity())).nextValue();
        }

        throw new MethodCallException("Method returned unexpected status code " + String.valueOf(statusCode));
    } catch (IOException e) {
        throw new MethodCallException("Call to " + methodName + " failed", e);
    } catch (JSONException e) {
        throw new FormatException("Call to " + methodName + " failed due to wrong response format", e);
    }
}

From source file:edu.cornell.mannlib.ld4lindexing.triplestores.MinimalVirtuosoTripleStore.java

/**
 * <pre>/*from  w  w w  .j av  a  2 s .c  o  m*/
 *     def sparql_query(sparql, format='application/sparql-results+json', &block)
 *       params = {'query' => sparql}
 *       headers = {'accept' => format}
 *       http_post("http://localhost:#{@http_port}/sparql/", block, params, headers)
 *     end
 * </pre>
 */
@Override
public JSONObject sparqlQuery(String query) {
    try {
        HttpPost method = new HttpPost("http://localhost:8890/sparql/");
        method.addHeader("Accept", "application/sparql-results+json");

        method.setEntity(new UrlEncodedFormEntity(Arrays.asList(new BasicNameValuePair("query", query))));
        HttpResponse response = httpClientHolder.get().execute(method);
        int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode > 399) {
            log.error("response " + statusCode + " to SPARQL query. \n");
        }
        try (InputStream in = response.getEntity().getContent()) {
            String json = new String(StreamUtils.getBytes(in));
            log.debug("SPARQL QUERY RESPONSE: " + json);
            return new JSONObject(json);
        }

    } catch (IllegalStateException | IOException | JSONException e) {
        log.error("Failure in SPARQL query", e);
        throw new RuntimeException(e);
    }
}