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:io.liveoak.pgsql.TestHelper.java

@Test
public void createUsersTable() throws IOException {
    HttpPost post = new HttpPost(ENDPOINT);
    post.setHeader(HttpHeaders.Names.CONTENT_TYPE, APPLICATION_JSON);
    post.setHeader(HttpHeaders.Names.ACCEPT, APPLICATION_JSON);

    String json = "{                                                             \n"
            + "  'id': 'users',                                                    \n"
            + "  'columns': [                                                      \n"
            + "     {                                                              \n"
            + "       'name': 'user_id',                                           \n"
            + "       'type': 'varchar',                                           \n"
            + "       'size': 40                                                   \n"
            + "     },                                                             \n"
            + "     {                                                              \n"
            + "       'name': 'nick',                                              \n"
            + "       'type': 'varchar',                                           \n"
            + "       'size': 60,                                                  \n"
            + "       'nullable': false,                                           \n"
            + "       'unique': true                                               \n"
            + "     },                                                             \n"
            + "     {                                                              \n"
            + "       'name': 'last_login',                                        \n"
            + "       'type': 'timestamp',                                         \n"
            + "       'nullable': false                                            \n"
            + "     }],                                                            \n"
            + "  'primary-key': ['user_id']                                        \n" + "}";

    String result = postRequest(post, json);
    System.out.println(result);//w ww  .  jav a2 s . c o  m

    String expected = "{                                                         \n"
            + "  'id': 'users;schema',                                             \n"
            + "  'self' : {                                                        \n" + "    'href' : '/" + APP
            + "/" + RESOURCE + "/users;schema'           \n"
            + "   },                                                               \n"
            + "  'columns': [                                                      \n"
            + "     {                                                              \n"
            + "       'name': 'user_id',                                           \n"
            + "       'type': 'varchar',                                           \n"
            + "       'size': 40,                                                  \n"
            + "       'nullable': false,                                           \n"
            + "       'unique': true                                               \n"
            + "     },                                                             \n"
            + "     {                                                              \n"
            + "       'name': 'nick',                                              \n"
            + "       'type': 'varchar',                                           \n"
            + "       'size': 60,                                                  \n"
            + "       'nullable': false,                                           \n"
            + "       'unique': true                                               \n"
            + "     },                                                             \n"
            + "     {                                                              \n"
            + "       'name': 'last_login',                                        \n"
            + "       'type': 'timestamp',                                         \n"
            + "       'size': 29,                                                  \n"
            + "       'nullable': false,                                           \n"
            + "       'unique': false                                              \n"
            + "     }],                                                            \n"
            + "  'primary-key': ['user_id'],                                       \n"
            + "  'ddl' : 'CREATE TABLE \"" + schema
            + "\".\"users\" (\"user_id\" varchar (40), \"nick\" varchar (60) UNIQUE NOT NULL, "
            + "\"last_login\" timestamp NOT NULL, PRIMARY KEY (\"user_id\"))'       \n" + "}";

    checkResult(result, expected);
}

From source file:org.jenkinsci.plugins.relution_publisher.net.requests.EntityRequest.java

private HttpUriRequest createHttpRequest(final Method method, final String uri, final HttpEntity entity) {

    switch (method) {
    default://  ww w .ja  v a 2s .c om
    case GET:
        return new HttpGet(uri);

    case POST:
        final HttpPost post = new HttpPost(uri);
        if (entity != null) {
            post.setEntity(entity);
        }
        return post;

    case PUT:
        final HttpPut put = new HttpPut(uri);
        if (entity != null) {
            put.setEntity(entity);
        }
        return put;

    case DELETE:
        return new HttpDelete(uri);
    }
}

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");
        }/*from   w  ww. j  ava  2  s  .  c  o  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:com.aikidonord.utils.JSONRequest.java

public JSONObject getJSONFromUrl(String url) {

    // Making HTTP request
    try {/*from ww  w  . ja va  2s  . c  o  m*/
        // defaultHttpClient
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);

        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, "utf-8"), 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());
    }

    //System.out.println("AIKIDONORD : " + json);
    // 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 null;
    }

    // return JSON String
    return jObj;

}

From source file:gertjvr.slacknotifier.SlackApiProcessor.java

public void sendNotification(String url, SlackNotificationMessage notification) throws IOException {
    String content = new Gson().toJson(notification);
    logger.debug(String.format("sendNotification: %s", content));

    CloseableHttpClient httpClient = HttpClients.createDefault();
    HttpPost httpPost = new HttpPost(url);

    httpPost.setEntity(new StringEntity(content, ContentType.APPLICATION_JSON));
    CloseableHttpResponse response = httpClient.execute(httpPost);

    try {/*w  ww.j a v  a 2s . com*/
        HttpEntity entity = response.getEntity();
        EntityUtils.consume(entity);
    } catch (Exception ex) {
        logger.error(String.format("sendNotification %s", ex.getMessage()), ex);
    } finally {
        response.close();
    }
}

From source file:com.ctg.itrdc.janus.rpc.protocol.hessian.HttpClientConnection.java

public HttpClientConnection(HttpClient httpClient, URL url) {
    this.httpClient = httpClient;
    this.output = new ByteArrayOutputStream();
    this.request = new HttpPost(url.toString());
}

From source file:org.fcrepo.integration.auth.oauth.api.TokenEndpointIT.java

@Test
public void testGetToken() throws Exception {
    logger.trace("Entering testGetToken()...");
    final HttpPost post = new HttpPost(
            tokenEndpoint + "?grant_type=password&username=foo&password=bar&client_secret=foo&client_id=bar");
    post.addHeader("Accept", APPLICATION_JSON);
    post.addHeader("Content-type", APPLICATION_FORM_URLENCODED);
    final HttpResponse tokenResponse = client.execute(post);
    logger.debug("Got a token response: \n{}", EntityUtils.toString(tokenResponse.getEntity()));
    Assert.assertEquals("Couldn't retrieve a token from token endpoint!", 200,
            tokenResponse.getStatusLine().getStatusCode());

}

From source file:com.shareplaylearn.resources.test.AccessTokenTest.java

public OauthPasswordFlow.LoginInfo testPost() throws IOException {
    HttpPost httpPost = new HttpPost(ACCESS_TOKEN_RESOURCE);
    String credentialsString = username + ":" + password;
    httpPost.addHeader("Authorization",
            Base64.encodeBase64String(credentialsString.getBytes(StandardCharsets.UTF_8)));

    try (CloseableHttpResponse response = BackendTest.httpClient.execute(httpPost)) {
        BackendTest.ProcessedHttpResponse processedHttpResponse = new BackendTest.ProcessedHttpResponse(
                response);//from   w  ww . jav a2  s  . c o  m
        if (response.getStatusLine().getStatusCode() != 200) {
            throw new RuntimeException(
                    "Error testing access token endpoint: " + processedHttpResponse.completeMessage);
        }
        return new Gson().fromJson(processedHttpResponse.entity, OauthPasswordFlow.LoginInfo.class);
    }
}

From source file:com.microsoft.windowsazure.core.tracing.util.JavaTracingInterceptorTest.java

@Test
public void testInformationSendRequest() {
    // Arrange/*ww w.j  av a 2 s  . com*/
    logContent = new ByteArrayOutputStream();
    System.setErr(new PrintStream(logContent));

    CloudTracing.addTracingInterceptor(new JavaTracingInterceptor());

    HttpRequest httpRequest = new HttpPost("http://www.bing.com");

    // Set Headers
    httpRequest.setHeader("Content-Type", "application/xml");
    httpRequest.setHeader("x-ms-version", "2012-03-01");

    // Act
    CloudTracing.sendRequest("test", httpRequest);

    // Assert
    String result = logContent.toString();
    assertTrue(result.contains("INFO: invocationId: test\r\nrequest: POST http://www.bing.com HTTP/1.1"));

    CloudTracing.information("hello there");
    result = logContent.toString();
    assertTrue(result.contains("INFO: hello there"));
}

From source file:de.micromata.genome.tpsb.httpmockup.HttpClientRequestAcceptor.java

private HttpPost buildMethod(MockHttpServletRequest request) {
    HttpPost ret;/*from  w w  w  .j  a  v  a  2  s .c  o  m*/
    if (StringUtils.equals(request.getMethod(), "POST") == true) {
        HttpPost pm = new HttpPost(baseUrl + request.getPathInfo());
        pm.setEntity(new ByteArrayEntity(request.getRequestData()));
        ret = pm;
    } else {
        throw new UnsupportedOperationException("Currently only POST methods are supported");
    }
    return ret;
}