Example usage for org.apache.http.client.methods HttpPost HttpPost

List of usage examples for org.apache.http.client.methods HttpPost HttpPost

Introduction

In this page you can find the example usage for org.apache.http.client.methods HttpPost HttpPost.

Prototype

public HttpPost(final String uri) 

Source Link

Usage

From source file:au.edu.anu.portal.portlets.basiclti.support.HttpSupport.java

/**
 * Make a POST request with the given Map of parameters to be encoded
 * @param address   address to POST to/*ww w . j  ava 2 s .c om*/
 * @param params   Map of params to use as the form parameters
 * @return
 */
public static String doPost(String address, Map<String, String> params) {

    HttpClient httpclient = new DefaultHttpClient();

    try {

        HttpPost httppost = new HttpPost(address);

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

        for (Map.Entry<String, String> entry : params.entrySet()) {
            formparams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
        }
        UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, HTTP.UTF_8);

        httppost.setEntity(entity);

        HttpResponse response = httpclient.execute(httppost);
        String responseContent = EntityUtils.toString(response.getEntity());

        return responseContent;

    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        httpclient.getConnectionManager().shutdown();
    }

    return null;
}

From source file:io.tourniquet.junit.http.rules.examples.HttpClientHelper.java

public static HttpPost post(String url, byte[] data) throws UnsupportedEncodingException {

    HttpPost post = new HttpPost(url);
    post.setEntity(new ByteArrayEntity(data));
    return post;//w  ww .jav  a  2 s  .co  m
}

From source file:br.com.atmatech.sac.webService.WebServiceAtivacao.java

public Boolean login(String url, String user, String password, String cnpj) throws IOException {
    Boolean chave = false;/*  w w w .ja v  a 2 s.co  m*/
    HttpPost post = new HttpPost(url);
    boolean result = false;
    /* Configura os parmetros do POST */
    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
    nameValuePairs.add(new BasicNameValuePair("login", user));
    nameValuePairs.add(new BasicNameValuePair("senha", password));
    post.setEntity(new UrlEncodedFormEntity(nameValuePairs, Consts.UTF_8));

    HttpResponse response = client.execute(post);

    EntityUtils.consume(response.getEntity());
    HttpGet get = new HttpGet("http://atma.serveftp.com/atma/view/nav/header_chave.php?cnpj=" + cnpj);
    response = client.execute(get);

    BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
    String line;
    FileWriter out = new FileWriter("./ativacao.html");
    PrintWriter gravarArq = new PrintWriter(out);
    while ((line = rd.readLine()) != null) {
        gravarArq.print(line + "\n");
        chave = true;
    }
    out.close();
    return chave;
}

From source file:org.sonar.plugins.buildstability.ci.jenkins.JenkinsUtils.java

public static void doLogin(HttpClient client, String hostName, String username, String password)
        throws IOException {
    String hudsonLoginEntryUrl = hostName + "/login";
    HttpGet loginLink = new HttpGet(hudsonLoginEntryUrl);
    HttpResponse response = client.execute(loginLink);
    checkResult(response.getStatusLine().getStatusCode(), hudsonLoginEntryUrl);
    EntityUtils.consume(response.getEntity());

    String location = hostName + "/j_acegi_security_check";
    boolean loggedIn = false;
    while (!loggedIn) {
        HttpPost loginMethod = new HttpPost(location);
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair("j_username", username));
        nvps.add(new BasicNameValuePair("j_password", password));
        nvps.add(new BasicNameValuePair("action", "login"));
        loginMethod.setEntity(new UrlEncodedFormEntity(nvps));
        try {// www.  j a  v  a 2s  .  com
            HttpResponse response2 = client.execute(loginMethod);
            if (response2.getStatusLine().getStatusCode() / 100 == 3) {
                // Commons HTTP client refuses to handle redirects for POST
                // so we have to do it manually.
                location = response2.getFirstHeader("Location").getValue();
            } else {
                checkResult(response2.getStatusLine().getStatusCode(), location);
                loggedIn = true;
            }
            EntityUtils.consume(response2.getEntity());
        } finally {
            loginMethod.releaseConnection();
        }
    }
}

From source file:Main.java

public static HttpEntity getEntity(String uri, ArrayList<BasicNameValuePair> params, int method)
        throws ClientProtocolException, IOException {
    mClient = new DefaultHttpClient();
    HttpUriRequest request = null;//from w  ww .  j  a  va  2  s.c o  m
    switch (method) {
    case METHOD_GET:
        StringBuilder sb = new StringBuilder(uri);
        if (params != null && !params.isEmpty()) {
            sb.append("?");
            for (BasicNameValuePair param : params) {
                sb.append(param.getName()).append("=").append(URLEncoder.encode(param.getValue(), "UTF_8"))
                        .append("&");
            }
            sb.deleteCharAt(sb.length() - 1);
        }
        request = new HttpGet(sb.toString());
        break;
    case METHOD_POST:
        HttpPost post = new HttpPost(uri);
        if (params != null && !params.isEmpty()) {
            UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params, "UTF_8");
            post.setEntity(entity);
        }
        request = post;
        break;
    }
    mClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 5000);
    mClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 5000);
    HttpResponse response = mClient.execute(request);
    System.err.println(response.getStatusLine().toString());
    if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
        return response.getEntity();
    }
    return null;
}

From source file:com.google.appengine.tck.misc.http.support.Client.java

public String post(String url) throws Exception {
    HttpPost post = new HttpPost(url);
    HttpResponse response = getClient().execute(post);
    Assert.assertEquals(200, response.getStatusLine().getStatusCode());
    return EntityUtils.toString(response.getEntity());
}

From source file:vng.paygate.notify.NotifyHelper.java

public String postNotify(String url, JsonObject json, String dataType, String contentType)
        throws UnsupportedEncodingException, IOException {
    try {//  w  w  w. j  av  a2s .c  o  m
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);
        if (StringUtils.isEmpty(contentType)) {
            contentType = "application/json";
        }
        if (StringUtils.isEmpty(dataType)) {
            dataType = "application/json";
        }
        httpPost.setHeader("Content-type", contentType);
        httpPost.setHeader("Accept-Content Type", dataType);
        httpPost.setEntity(new StringEntity(json.toString()));
        CloseableHttpResponse httpResponse = httpClient.execute(httpPost);
        if (httpResponse.getStatusLine().getStatusCode() == 200) {
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(httpResponse.getEntity().getContent()));
            String inputLine;
            StringBuffer response = new StringBuffer();
            while ((inputLine = reader.readLine()) != null) {
                response.append(inputLine);
            }
            reader.close();
            return response.toString();
        } else {
            return "";
        }
    } catch (Exception e) {
        return "";
    }
}

From source file:com.cats.version.utils.Utils.java

public static String postMsgAndGet(String msg) {
    HttpPost request = new HttpPost(UserPreference.getInstance().getUrl());
    List<NameValuePair> parameters = new ArrayList<NameValuePair>();
    parameters.add(new BasicNameValuePair("msg", msg));

    try {//from w  w w . jav a  2  s .  com
        UrlEncodedFormEntity formEntiry = new UrlEncodedFormEntity(parameters, IVersionConstant.CHARSET_UTF8);
        request.setEntity(formEntiry);
        HttpResponse response = client.execute(request);
        if (response.getStatusLine().getStatusCode() == 200) {
            return EntityUtils.toString(response.getEntity(), IVersionConstant.CHARSET_UTF8);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

From source file:com.grepsound.requests.GoogleLoginRequest.java

@Override
public Token loadDataFromNetwork() throws Exception {

    //        Request req = new Request("https://api.soundcloud.com/oauth2/token");

    HttpPost req = new HttpPost("https://api.soundcloud.com/oauth2/token");

    JSONObject body = new JSONObject();
    body.put("access_token", mGToken);
    body.put("scope", Token.SCOPE_NON_EXPIRING);

    ApiWrapper wrapper = new ApiWrapper(SpiceUpService.CLIENT_ID, SpiceUpService.CLIENT_SECRET, null, null);
    HttpClient client = wrapper.getHttpClient();

    HttpResponse response = client.execute(req);

    Log.i("G+REQUEST", response.getEntity().toString());

    return null;//from  www  . ja  v a 2s  .co  m
}

From source file:com.oracle.jes.samples.hellostorage.httpcPoster1.java

public String putMessage(int i, String vel, String ser) {

    String out = null;/*  w ww .ja v  a2 s. c  o  m*/

    HttpClient httpclient = HttpClientBuilder.create().build();

    HttpPost httppostreq = new HttpPost("http://192.168.1.5:8080/async-request-war/AjaxCometServlet");
    //HttpPost httppostreq = new HttpPost("http://192.168.1.5:8080/pichrony/AjaxCometServlet");

    //HttpPost httppostreq = new HttpPost("http://192.168.1.5:8080/async-request-war/AjServlet");

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

    if (i == 1) {
        pairs.add(new BasicNameValuePair("action", "login"));
        pairs.add(new BasicNameValuePair("name", ser));
    } else {
        FindMac fm = new FindMac();

        String m = fm.getAddr();

        pairs.add(new BasicNameValuePair("action", "post"));
        pairs.add(new BasicNameValuePair("name", ser));
        pairs.add(new BasicNameValuePair("message", vel));

    }

    try {
        httppostreq.setEntity(new UrlEncodedFormEntity(pairs));
    } catch (UnsupportedEncodingException e1) {
        // TODO Auto-generated catch block
        //e1.printStackTrace();
    }

    /*
    StringEntity se=null;
    try {
       se = new StringEntity(jsono.toString());
    } catch (UnsupportedEncodingException e) {
       // TODO Auto-generated catch block
       e.printStackTrace();
    }
            
            
            
    se.setContentType("application/json;charset=UTF-8");
    se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json;charset=UTF-8"));
    httppostreq.setEntity(se);
    */

    //HttpGet httpget = new HttpGet("http://192.168.1.5:8080/async-request-war/AjServlet");

    try {
        HttpResponse response = httpclient.execute(httppostreq);

        if (response != null) {
            out = "";
            InputStream inputstream = response.getEntity().getContent();
            out = convertStreamToString(inputstream);

        } else {

        }
    } catch (ClientProtocolException e) {

    } catch (IOException e) {
    } catch (Exception e) {
    }
    return out;
}