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.ea.core.bridge.ws.rest.client.PostClient.java

@Override
protected HttpRequestBase getMethod(String url) {
    // TODO Auto-generated method stub
    return new HttpPost(url);
}

From source file:org.smartloli.kafka.eagle.common.util.TestHttpClientUtils.java

private static HttpPost createHttpPost(Map<String, Object> dingDingMarkdownMessage) {
    if (WEBHOOK_TOKEN == null || WEBHOOK_TOKEN.trim().isEmpty()) {
        return null;
    }/*from  w  w w . j a  v  a2s. c om*/
    HttpPost httpPost = new HttpPost(WEBHOOK_TOKEN);
    httpPost.addHeader("Content-Type", "application/json; charset=utf-8");
    StringEntity sEntity = new StringEntity(JSONObject.toJSONString(dingDingMarkdownMessage), "utf-8");
    httpPost.setEntity(sEntity);
    return httpPost;
}

From source file:RGSOplataRu.OplataConnection.java

@Override
public String POST_Request(String p_uri, Object... p_objects) throws IOException {
    String result = "";
    HttpPost request = new HttpPost(p_uri);
    request = getRequestConfigurator().Configurate(request);

    if (p_objects.length > 0) {
        HttpEntity reqEntity = EntityBuilder.create().setText((String) p_objects[0])
                .setContentType(ContentType.create(request.getFirstHeader("Content-Type").getValue(),
                        Charset.forName(request.getFirstHeader("charset").getValue())))
                .build();/*w  w w.  j  a  v  a2s .  com*/

        request.setEntity(reqEntity);
        //            System.out.println("target= "+target);
        //            System.out.println("httpClient= "+httpClient);
        //            System.out.println("request= "+request.getFirstHeader("charset").getValue());
        //            System.out.println("request= "+request.getFirstHeader("Content-Type").getValue());
        //            System.out.println("request entity= " + request.getEntity());

        //            System.out.println("request headers:");
        //            for( Header h : request.getAllHeaders()){
        //                
        //                System.out.println(h.getName() + ":" + h.getValue());
        //            }
        CloseableHttpResponse responce = httpClient.execute(target, request);
        result = responceToString(responce);
    }

    return result;
}

From source file:com.fdesousa.android.WheresMyTrain.Library.json.TflJsonFetcher.java

/**
 * Utility method for fetching an InputStream from a designated URI
 * and returning it for processing.<br/>
 * Static method to aide in easy, wide-spread use
 * @param uri - the URI of the data to fetch
 * @return InputStream containing the response of the request
 * @throws IllegalStateException - in case of a problem, or if connection was aborted
 * @throws IOException - if the stream could not be created
 *///  www .  j  a va2  s  .co m
public static InputStream fetchNewJson(URI uri) throws IllegalStateException, IOException {
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost(uri);
    HttpResponse httpresponse = httpclient.execute(httppost);
    HttpEntity entity = httpresponse.getEntity();

    return entity.getContent();
}

From source file:org.factpub.ui.gui.network.PostFile.java

public static List<String> uploadToFactpub(File file) throws Exception {
    List<String> status = new ArrayList<String>();
    int i = 0;/*from   w  w w.  j a  va2  s  .c  om*/

    HttpClient httpclient = new DefaultHttpClient();
    httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);

    String postUrl = FEConstants.SERVER_POST_HANDLER + "?id=" + AuthMediaWikiIdHTTP.authorisedUser + "&ps="
            + AuthMediaWikiIdHTTP.userPassword;

    HttpPost httppost = new HttpPost(postUrl);

    System.out.println(postUrl);

    MultipartEntity mpEntity = new MultipartEntity();
    ContentBody cbFile = new FileBody(file, "json");

    // name must be "uploadfile". this is same on the server side.
    mpEntity.addPart(FEConstants.SERVER_UPLOAD_FILE_NAME, cbFile);

    httppost.setEntity(mpEntity);
    System.out.println("executing request " + httppost.getRequestLine());
    HttpResponse response = httpclient.execute(httppost);
    HttpEntity resEntity = response.getEntity();

    System.out.println(response.getStatusLine());

    if (response.getStatusLine().toString().contains("502 Bad Gateway")) {
        status.add("Looks server is down.");
    } else {
        if (resEntity != null) {
            status.add(EntityUtils.toString(resEntity));
            System.out.println(status.get(i));
            i++;
        }

        if (resEntity != null) {
            resEntity.consumeContent();
        }
    }
    httpclient.getConnectionManager().shutdown();

    //String status = "Upload Success!";
    return status;
}

From source file:org.wso2.carbon.integration.test.client.HttpEventPublisherClient.java

public static void publish(String url, String username, String password, String testCaseFolderName,
        String dataFileName) {//from ww  w  .  j a va  2s  .com
    log.info("Starting WSO2 HttpEventPublisher Client");
    KeyStoreUtil.setTrustStoreParams();
    HttpClient httpClient = new SystemDefaultHttpClient();
    try {
        HttpPost method = new HttpPost(url);
        List<String> messagesList = readMsg(getTestDataFileLocation(testCaseFolderName, dataFileName));
        for (String message : messagesList) {
            StringEntity entity = new StringEntity(message);
            log.info("Sending message:");
            log.info(message + "\n");
            method.setEntity(entity);
            if (url.startsWith("https")) {
                processAuthentication(method, username, password);
            }
            httpClient.execute(method).getEntity().getContent().close();
            Thread.sleep(1000);
        }
        Thread.sleep(500); // Waiting time for the message to be sent

    } catch (Throwable t) {
        log.error("Error when sending the messages", t);
    }
}

From source file:org.opencastproject.remotetest.server.resource.IngestResources.java

/**
 * /*w  ww .j a  v a 2 s  . c  o  m*/
 * @param type
 *          Type of media to add: Track, Catalog, Attachment
 * 
 */
public static HttpResponse add(TrustedHttpClient client, String type, String url, String flavor,
        String mediaPackage) throws Exception {
    HttpPost post = new HttpPost(getServiceUrl() + "add" + type);
    List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
    params.add(new BasicNameValuePair("url", url));
    params.add(new BasicNameValuePair("flavor", flavor));
    params.add(new BasicNameValuePair("mediaPackage", mediaPackage));
    post.setEntity(new UrlEncodedFormEntity(params));
    return client.execute(post);
}

From source file:com.portfolio.data.utils.PostForm.java

public static boolean sendFile(String sessionid, String backend, String user, String uuid, String lang,
        File file) throws Exception {
    CloseableHttpClient httpclient = HttpClients.createDefault();

    try {/*w  w w  .ja  v  a 2  s  .  c o m*/
        // Server + "/resources/resource/file/" + uuid +"?lang="+ lang
        // "http://"+backend+"/user/"+user+"/file/"+uuid+"/"+lang+"ptype/fs";
        String url = "http://" + backend + "/resources/resource/file/" + uuid + "?lang=" + lang;
        HttpPost post = new HttpPost(url);
        post.setHeader("Cookie", "JSESSIONID=" + sessionid); // So that the receiving servlet allow us

        /// Remove import language tag
        String filename = file.getName(); /// NOTE: Since it's used with zip import, specific code.
        int langindex = filename.lastIndexOf("_");
        filename = filename.substring(0, langindex) + filename.substring(langindex + 3);

        FileBody bin = new FileBody(file, ContentType.DEFAULT_BINARY, filename); // File from import

        /// Form info
        HttpEntity reqEntity = MultipartEntityBuilder.create().addPart("uploadfile", bin).build();
        post.setEntity(reqEntity);

        CloseableHttpResponse response = httpclient.execute(post);

        /*
        try
        {
           HttpEntity resEntity = response.getEntity();   /// Will be JSON
           if( resEntity != null )
           {
              BufferedReader reader = new BufferedReader(new InputStreamReader(resEntity.getContent(), "UTF-8"));
              StringBuilder builder = new StringBuilder();
              for( String line = null; (line = reader.readLine()) != null; )
          builder.append(line).append("\n");
                
              updateResource( sessionid, backend, uuid, lang, builder.toString() );
           }
           EntityUtils.consume(resEntity);
        }
        finally
        {
           response.close();
        }
        //*/
    } finally {
        httpclient.close();
    }

    return true;
}

From source file:communication.Communicator.java

/**
 * Adds a new trackingPosition to an existing cartracker
 *
 * @param tracker The cartracker with a new trackingPosition
 * @return The serialnumber of the new trackingPosition
 * @throws IOException/*ww w. j  av a2 s .  c  o  m*/
 */
public static Long postTrackingPositionsForTracker(CarTracker tracker) throws IOException {
    Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ss").create();
    CloseableHttpClient httpClient = HttpClientBuilder.create().build();
    HttpPost post = new HttpPost(BASE_URL_PRODUCTION + "/" + tracker.getId() + "/movements");
    String jsonBody = gson.toJson(tracker.getCurrentTrackingPeriod());
    StringEntity postingString = new StringEntity(jsonBody, CHARACTER_SET);
    post.setEntity(postingString);
    post.setHeader(HTTP.CONTENT_TYPE, "application/json");
    HttpResponse response = httpClient.execute(post);

    String responseString = EntityUtils.toString(response.getEntity(), CHARACTER_SET);
    JSONObject json = new JSONObject(responseString);
    return json.getLong("serialNumber");
}

From source file:com.verizon.ExportDataToServer.java

public void sendDataToRESTService(String data) {

    try {/*from   w ww  .  j  a  va2  s .c om*/
        String url = "http://localhost:8080";

        HttpClient client = HttpClientBuilder.create().build();
        HttpPost post = new HttpPost(url);
        List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
        urlParameters.add(new BasicNameValuePair("data", data));

        HttpEntity stringEnt = new StringEntity(data);
        post.setEntity(stringEnt);

        HttpResponse response = client.execute(post);
        System.out.println("Response Code : " + response.getStatusLine().getStatusCode());
    } catch (IOException ex) {
        System.out.println("Unable to send data to streaming service..");
    }

}