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:net.oebs.jalos.Client.java

public SubmitResponseObject submit(String postUrl) throws IOException {
    HttpPost httpPost = new HttpPost(this.serviceUrl + "/a/submit");
    List<NameValuePair> nvps = new ArrayList<NameValuePair>();
    nvps.add(new BasicNameValuePair("url", postUrl));
    httpPost.setEntity(new UrlEncodedFormEntity(nvps));
    CloseableHttpResponse response = httpClient.execute(httpPost);
    HttpEntity entity = response.getEntity();

    ObjectMapper mapper = new ObjectMapper();
    SubmitResponseObject sro = mapper.readValue(entity.getContent(), SubmitResponseObject.class);

    EntityUtils.consume(entity);//from w  w  w  .  j  a va 2s .c  o  m
    response.close();
    return sro;
}

From source file:org.wso2.developerstudio.appfactory.core.client.HttpsJaggeryClient.java

public static String httpPostLogin(String urlStr, Map<String, String> params) {

    client = new DefaultHttpClient();
    client = HttpsJaggeryClient.wrapClient(client, urlStr);

    HttpPost post = new HttpPost(urlStr);
    String respond = "";
    HttpResponse response = null;/*from  w ww.  j  a v  a  2 s  .  c  o  m*/

    try {
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
        Set<String> keySet = params.keySet();

        for (String key : keySet) {
            nameValuePairs.add(new BasicNameValuePair(key, params.get(key)));
        }
        post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        response = client.execute(post);

        if (200 == response.getStatusLine().getStatusCode()) {
            cookie = response.getFirstHeader("Set-Cookie").getValue().split(";")[0];
            HttpEntity entityGetAppsOfUser = response.getEntity();
            BufferedReader rd = new BufferedReader(new InputStreamReader(entityGetAppsOfUser.getContent()));
            StringBuilder sb = new StringBuilder();
            String line = "";

            while ((line = rd.readLine()) != null) {
                sb.append(line);
            }
            respond = sb.toString();

            if ("false".equals(respond)) {
                Authenticator.getInstance().setErrorcode(ErrorType.INVALID);
            }
            EntityUtils.consume(entityGetAppsOfUser);

            if (entityGetAppsOfUser != null) {
                entityGetAppsOfUser.getContent().close();
            }
        } else {
            Authenticator.getInstance().setErrorcode(ErrorType.FAILD);
            Authenticator.getInstance().setErrormsg(response.getStatusLine().getReasonPhrase());
            log.error("(" + response.getStatusLine().getStatusCode() + ")" + ":"
                    + response.getStatusLine().getReasonPhrase());
            return "false";
        }

    } catch (Exception e) {
        Authenticator.getInstance().setErrorcode(ErrorType.ERROR);
        log.error("Connection failure", e);
        return "false";
    } finally {
        client.getConnectionManager().closeExpiredConnections();
    }

    return respond;
}

From source file:org.kei.android.phone.mangastore.http.HttpTaskRemove.java

@Override
protected JSONArray doInBackground(final String... params) {
    try {// w w w  .  j  a va  2  s.  c  om
        final HttpClient client = new DefaultHttpClient();
        final HttpPost httpPost = new HttpPost(params[0]);
        final List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
        nameValuePairs.add(new BasicNameValuePair("android_name", params[1]));
        nameValuePairs.add(new BasicNameValuePair("android_password", params[2]));
        nameValuePairs.add(new BasicNameValuePair("android_i", params[3]));
        httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        final HttpResponse response = client.execute(httpPost);
        final StatusLine statusLine = response.getStatusLine();
        final int code = statusLine.getStatusCode();
        if (code != 200) {
            throw new IOException("The server has responded an error " + code);
        }
    } catch (final Exception e) {
        t.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                t.onTaskError(e);
            }
        });
    }
    return null;
}

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

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

    try {/*from   w w  w. ja va2  s.  c o m*/
        List<NameValuePair> params = new ArrayList<NameValuePair>();

        params.add(new BasicNameValuePair("method", "freezers"));
        params.add(new BasicNameValuePair("username", _username));
        params.add(new BasicNameValuePair("password", _password));

        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 GetFreezersResponse(_export, handler.handleResponse(response), status.getStatusCode(),
                    job);
        else
            return new GetFreezersResponse(_export, status.getReasonPhrase(), status.getStatusCode(), job);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:eu.seaclouds.platform.dashboard.http.HttpPostRequestBuilder.java

public String build() throws IOException, URISyntaxException {
    if (!params.isEmpty() && entity == null) {
        if (!isMultipart) {
            this.entity = new UrlEncodedFormEntity(params);
        } else {/*w  ww .j a va2s.  c om*/
            MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
            for (NameValuePair pair : params) {
                entityBuilder.addTextBody(pair.getName(), pair.getValue());
            }

            this.entity = entityBuilder.build();
        }
    }

    URI uri = new URIBuilder().setHost(host).setPath(path).setScheme(scheme).build();

    this.requestBase = new HttpPost(uri);

    for (NameValuePair header : super.headers) {
        requestBase.addHeader(header.getName(), header.getValue());
    }

    try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
        if (this.entity != null) {
            this.requestBase.setEntity(this.entity);
        }
        return httpClient.execute(requestBase, responseHandler, context);
    }
}

From source file:com.ammobyte.radioreddit.api.PerformSave.java

@Override
protected Void doInBackground(String... params) {
    final String modhash = params[0];
    final String cookie = params[1];
    final String id = params[2];
    final String type = params[3];

    // Prepare POST with cookie and execute it
    try {/*from  ww w. j ava 2  s.c  om*/
        final HttpClient httpClient = new DefaultHttpClient();
        final HttpPost httpPost = new HttpPost("http://www.reddit.com/api/" + type);
        final List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
        nameValuePairs.add(new BasicNameValuePair("id", id));
        nameValuePairs.add(new BasicNameValuePair("uh", modhash));
        httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        // Using HttpContext, CookieStore, and friends didn't work
        httpPost.setHeader("Cookie", "reddit_session=" + cookie);
        httpPost.setHeader("User-Agent", RedditApi.USER_AGENT);
        httpClient.execute(httpPost);
        // We just assume that everything worked so there's no need to check the response
    } catch (UnsupportedEncodingException e) {
        Log.i(RedditApi.TAG, "UnsupportedEncodingException while performing vote", e);
    } catch (ClientProtocolException e) {
        Log.i(RedditApi.TAG, "ClientProtocolException while performing vote", e);
    } catch (IOException e) {
        Log.i(RedditApi.TAG, "IOException while performing vote", e);
    } catch (ParseException e) {
        Log.i(RedditApi.TAG, "ParseException while performing vote", e);
    }

    return null;
}

From source file:org.n52.sir.IT.TransformerBindingIT.java

@Test
public void readValidSensorMLAndValidate() throws IOException {
    File f = new File(ClassLoader.getSystemResource("AirBase-test.xml").getFile());
    BufferedReader reader = new BufferedReader(new FileReader(f));
    String s = null;/*from   w  w w . j a  va  2 s.co  m*/
    StringBuilder builder = new StringBuilder();
    while ((s = reader.readLine()) != null)
        builder.append(s);
    String sensorML = builder.toString();
    HttpPost post = new HttpPost("http://localhost:8080/OpenSensorSearch/convert/");
    List<NameValuePair> pairs = new ArrayList<NameValuePair>();
    pairs.add(new BasicNameValuePair("sensor", sensorML));
    pairs.add(new BasicNameValuePair("output", "ebrim"));
    post.setEntity(new UrlEncodedFormEntity(pairs));

    HttpClient client = new DefaultHttpClient();
    HttpResponse resp = client.execute(post);
    StringBuilder result = new StringBuilder();
    reader = new BufferedReader(new InputStreamReader(resp.getEntity().getContent()));
    while ((s = reader.readLine()) != null)
        result.append(s);
    //TODO yakoub : complete teh checking here

}

From source file:javafxapplication1.HttpClientExample.java

private 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);//  w w  w . j a v a 2  s  .c o  m
    }

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

}

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

public static String addLibrary(Library library) {

    List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
    urlParameters.add(new BasicNameValuePair("category_id", Integer.toString(library.getCategory_id())));
    urlParameters.add(new BasicNameValuePair("title", library.getTitle()));
    urlParameters.add(new BasicNameValuePair("published_date", library.getPublished_date()));
    urlParameters.add(new BasicNameValuePair("url", library.getUrl()));

    HttpResponse result;//from   w  w  w. j  a v  a2  s  .  c  o  m
    String resultStr = "";

    try {

        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost post = new HttpPost(Constants.INSERT_LIBRARY_RESOURCE);
        post.setEntity(new UrlEncodedFormEntity(urlParameters));
        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.example.yudiandrean.socioblood.databases.JSONParser.java

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

    // Making HTTP request
    try {//from  w  w  w.ja  va  2s  .co m
        // defaultHttpClient
        DefaultHttpClient httpClient = new DefaultHttpClient();
        httpClient.getParams().setParameter(ClientPNames.ALLOW_CIRCULAR_REDIRECTS, true);
        HttpPost httpPost = new HttpPost(url);
        httpPost.setEntity(new UrlEncodedFormEntity(params));

        HttpResponse httpResponse = httpClient.execute(httpPost);
        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();
        Log.e("JSON", json);
    } 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());
    }

    // return JSON String
    return jObj;

}