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:com.oracle.jes.samples.hellostorage.RegisterDevice.java

public String sendRecord(String m) {
    mode = false;/*from ww  w . ja v  a  2s.  c o  m*/
    String out = null;

    //   DefaultHttpClient httpclient = new DefaultHttpClient();
    HttpClient httpclient = HttpClientBuilder.create().build();

    HttpPost httppostreq;
    if (!mode) {

        httppostreq = new HttpPost("http://192.168.1.5:8080/pichrony/RegNewChrony");

    } else {
        httppostreq = new HttpPost("http://security.netmaxjava.com/phlogin");

    }

    StringEntity se = null;

    try {
        se = new StringEntity(m);
    } catch (UnsupportedEncodingException ex) {
        //Logger.getLogger(RegisterDevice.class.getName()).log(Level.SEVERE, null, ex);
    }

    //   se.setContentType("application/json;");

    httppostreq.setEntity(se);

    try {
        HttpResponse respo = httpclient.execute(httppostreq);
        if (respo != null) {
            out = "";
            InputStream inputstream = respo.getEntity().getContent();
            out = convertStreamToString(inputstream);

        } else {

        }
    } catch (ClientProtocolException e) {

    } catch (IOException | IllegalStateException e) {
    }
    return out;
}

From source file:org.epics.archiverappliance.retrieval.channelarchiver.XMLRPCClient.java

/**
 * Internal method to make a XML_RPC post call and call the SAX handler on the returned document.
 * @param serverURL The Server URL//from   w w w  .  j  a va 2  s.c om
 * @param handler  DefaultHandler 
 * @param postEntity StringEntity 
 * @throws IOException    
 * @throws SAXException    
 */
private static void doHTTPPostAndCallSAXHandler(String serverURL, DefaultHandler handler,
        StringEntity postEntity) throws IOException, SAXException {
    logger.debug("Executing doHTTPPostAndCallSAXHandler with the server URL " + serverURL);
    CloseableHttpClient httpclient = HttpClients.createDefault();
    HttpPost postMethod = new HttpPost(serverURL);
    postMethod.addHeader("Content-Type", "text/xml");
    postMethod.setEntity(postEntity);
    logger.debug("Executing the HTTP POST" + serverURL);
    HttpResponse response = httpclient.execute(postMethod);
    HttpEntity entity = response.getEntity();
    if (entity != null) {
        logger.debug("Obtained a HTTP entity of length " + entity.getContentLength());
        try (InputStream is = entity.getContent()) {
            SAXParserFactory sfac = SAXParserFactory.newInstance();
            sfac.setNamespaceAware(false);
            sfac.setValidating(false);
            SAXParser parser = sfac.newSAXParser();
            parser.parse(is, handler);
        } catch (ParserConfigurationException pex) {
            throw new IOException(pex);
        }
    } else {
        throw new IOException("HTTP response did not have an entity associated with it");
    }
}

From source file:com.arpnetworking.kairosdb.KairosHelper.java

/**
 * Creates the JSON body for a datapoint POST.
 *
 * @param timestamp timestamp of the datapoint
 * @param histogram the histogram/*from   w  w  w  . j  a v a2s.  c  o  m*/
 * @param metricName the name of the metric
 * @return JSON Array to POST to KairosDB
 * @throws JSONException on a JSON error
 */
public static HttpPost postHistogram(final int timestamp, final Histogram histogram, final String metricName)
        throws JSONException {
    final JSONArray json = new JSONArray();
    final JSONObject metric = new JSONObject();
    final JSONArray datapoints = new JSONArray();
    final JSONArray datapoint = new JSONArray();
    final JSONObject tags = new JSONObject();
    tags.put("host", "foo_host");

    datapoint.put(timestamp);
    datapoint.put(histogram.getJson());
    datapoints.put(datapoint);

    metric.put("name", metricName).put("ttl", 600).put("type", "histogram").put("datapoints", datapoints)
            .put("tags", tags);

    json.put(metric);
    final HttpPost post = new HttpPost(KairosHelper.getEndpoint() + "/api/v1/datapoints");
    try {
        post.setEntity(new StringEntity(json.toString()));
    } catch (final UnsupportedEncodingException e) {
        throw new RuntimeException(e);
    }
    post.addHeader(HttpHeaders.CONTENT_TYPE, "application/json");
    return post;
}

From source file:org.arquillian.graphene.visual.testing.test.RestUtilsTest.java

@Test
public void testResponse() {
    String token = "test-word";
    CloseableHttpClient httpClient = RestUtils.getHTTPClient(conf.getJcrContextRootURL(), conf.getJcrUserName(),
            conf.getJcrPassword());//from  w w w .  ja v  a 2 s  . co m
    HttpPost postCreateWords = new HttpPost(
            conf.getManagerContextRootURL() + "graphene-visual-testing-webapp/rest/words");
    StringEntity wordEnity = new StringEntity("{\"value\": \"" + token + "\"}", ContentType.APPLICATION_JSON);
    postCreateWords.setHeader("Content-Type", "application/json");
    postCreateWords.setEntity(wordEnity);
    String response = RestUtils.executePost(postCreateWords, httpClient, token + " created",
            "FAILED TO CREATE: " + token);
}

From source file:Logica.prueba.java

public prueba() {
    cliente = HttpClients.createDefault();
    post = new HttpPost(url);
    post.setHeader("Content-type", "application/json");
    try {/*from  w  ww.  ja  va 2s  .  co m*/
        key = getSessionKey();
    } catch (UnsupportedEncodingException ex) {
        Logger.getLogger(prueba.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:vic.collaborativeClouds.serverWorkers.HttpPostWorker.java

public String LoginPostRequest(String postUrl, String postJSONData) throws IOException, JSONException {
    try {//w w  w.j a v a  2  s  .c o  m
        HttpPost post = new HttpPost(postUrl);
        HttpClient httpClient = new DefaultHttpClient();
        StringEntity postingString = new StringEntity(postJSONData);
        post.setEntity(postingString);
        post.setHeader("Content-type", "application/json");
        HttpResponse response = httpClient.execute(post);
        String server = response.getFirstHeader("x-session").getValue();
        System.err.println(response.getFirstHeader("status").getValue());
        System.err.println(server);
        SessionStore.session_id = server;
        return response.getFirstHeader("status").getValue();
    } catch (UnsupportedEncodingException ex) {
        return "Failed";
        //Logger.getLogger(HttpPostWorker.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:com.project.utilities.Utilities.java

/**
 * Sends post request to sepcified URL//from  w ww . ja v  a  2 s.  co m
 * @param valuePairs
 * @param postUrl
 * @return
 */
public static String postRequest(final List<BasicNameValuePair> valuePairs, final String postUrl) {
    String responseStr = null;

    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
    StrictMode.setThreadPolicy(policy);

    HttpClient httpclient = new DefaultHttpClient();
    Log.e("POST_REQUEST", "ACTION LOGIN");
    HttpPost httppost = new HttpPost(postUrl);

    try {
        // Add your data
        List<NameValuePair> postFields = new ArrayList<NameValuePair>(2);
        for (BasicNameValuePair nameValuePair : valuePairs) {
            postFields.add(nameValuePair);
        }
        httppost.setEntity(new UrlEncodedFormEntity(postFields));

        // Execute HTTP Post Request
        HttpResponse response = httpclient.execute(httppost);
        responseStr = EntityUtils.toString(response.getEntity());
        Log.e("POST_REQUEST", "RESPONSE_CODE: " + response.getStatusLine().getStatusCode() + "");
    } catch (ClientProtocolException e) {
        Log.e("ClientProtocolException", e.getMessage().toString());
    } catch (IOException e) {
        Log.e("IOException", e.getMessage().toString());
    }

    return responseStr;
}

From source file:org.sakaiproject.contentreview.urkund.util.UrkundAPIUtil.java

public static String postDocument(String baseUrl, String receiverAddress, String externalId,
        UrkundSubmission submission, String urkundUsername, String urkundPassword, int timeout) {
    String ret = null;//from   ww  w  .  jav a 2s  .c o m

    RequestConfig.Builder requestBuilder = RequestConfig.custom();
    requestBuilder = requestBuilder.setConnectTimeout(timeout);
    requestBuilder = requestBuilder.setConnectionRequestTimeout(timeout);

    HttpClientBuilder builder = HttpClientBuilder.create();
    builder.setDefaultRequestConfig(requestBuilder.build());
    try (CloseableHttpClient httpClient = builder.build()) {

        HttpPost httppost = new HttpPost(baseUrl + "submissions/" + receiverAddress + "/" + externalId);
        //------------------------------------------------------------
        EntityBuilder eBuilder = EntityBuilder.create();
        eBuilder.setBinary(submission.getContent());

        httppost.setEntity(eBuilder.build());
        //------------------------------------------------------------
        if (StringUtils.isNotBlank(urkundUsername) && StringUtils.isNotBlank(urkundPassword)) {
            addAuthorization(httppost, urkundUsername, urkundPassword);
        }
        //------------------------------------------------------------
        httppost.addHeader("Accept", "application/json");
        httppost.addHeader("Content-Type", submission.getMimeType());
        httppost.addHeader("Accept-Language", submission.getLanguage());
        httppost.addHeader("x-urkund-filename", submission.getFilenameEncoded());
        httppost.addHeader("x-urkund-submitter", submission.getSubmitterEmail());
        httppost.addHeader("x-urkund-anonymous", Boolean.toString(submission.isAnon()));
        httppost.addHeader("x-urkund-subject", submission.getSubject());
        httppost.addHeader("x-urkund-message", submission.getMessage());
        //------------------------------------------------------------

        HttpResponse response = httpClient.execute(httppost);
        HttpEntity resEntity = response.getEntity();

        if (resEntity != null) {
            ret = EntityUtils.toString(resEntity);
            EntityUtils.consume(resEntity);
        }

    } catch (IOException e) {
        log.error("ERROR uploading File : ", e);
    }

    return ret;
}

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

public static String addWebinar(Webinar webinar) {
    List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
    urlParameters.add(new BasicNameValuePair("content_id", webinar.getContent_id().toString()));
    urlParameters.add(new BasicNameValuePair("presenter", webinar.getPresenter()));

    String resultStr = "";

    try {/*w ww  .j a  va 2 s .  co m*/

        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost post = new HttpPost(Constants.INSERT_WEBINAR_RESOURCE);
        post.setEntity(new UrlEncodedFormEntity(urlParameters));
        HttpResponse 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.grinnellplans.plandroid.LoginTask.java

protected String doInBackground(String... params) {
    Log.i("LoginTask::doInBackground", "entered");
    AndroidHttpClient plansClient = AndroidHttpClient.newInstance("plandroid");
    final HttpPost req = new HttpPost("http://" + _ss.get_serverName() + "/api/1/index.php?task=login");
    List<NameValuePair> postParams = new ArrayList<NameValuePair>(2);
    postParams.add(new BasicNameValuePair("username", params[0]));
    postParams.add(new BasicNameValuePair("password", params[1]));
    Log.i("LoginTask::doInBackground", "setting postParams");
    String resp = null;/* w  w  w.j a v  a 2 s .c o m*/
    try {
        req.setEntity(new UrlEncodedFormEntity(postParams));
        HttpResponse response = null;
        Log.i("LoginTask::doInBackground", "executing request");
        response = plansClient.execute(req, _httpContext);
        Log.i("LoginTask::doInBackground", "reading response");
        resp = new BufferedReader((new InputStreamReader(response.getEntity().getContent()))).readLine();
    } catch (Exception e) {
        resp = constructResponse(e);
    }
    plansClient.close();
    Log.i("LoginTask::doInBackground", "server responded \"" + resp + "\"");
    Log.i("LoginTask::doInBackground", "exit");
    return resp;
}