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:org.thoughtcrime.securesms.mms.MmsSendHelper.java

private static byte[] makePost(MmsConnectionParameters parameters, byte[] mms)
        throws ClientProtocolException, IOException {
    Log.w("MmsSender", "Sending MMS1 of length: " + mms.length);
    try {/*from  w w  w. jav a 2s. co m*/
        HttpClient client = constructHttpClient(parameters);
        URI hostUrl = new URI(parameters.getMmsc());
        HttpHost target = new HttpHost(hostUrl.getHost(), hostUrl.getPort(), HttpHost.DEFAULT_SCHEME_NAME);
        HttpPost request = new HttpPost(parameters.getMmsc());
        ByteArrayEntity entity = new ByteArrayEntity(mms);

        entity.setContentType("application/vnd.wap.mms-message");

        request.setEntity(entity);
        request.setParams(client.getParams());
        request.addHeader("Accept", "*/*, application/vnd.wap.mms-message, application/vnd.wap.sic");

        HttpResponse response = client.execute(target, request);
        StatusLine status = response.getStatusLine();

        if (status.getStatusCode() != 200)
            throw new IOException("Non-successful HTTP response: " + status.getReasonPhrase());

        return parseResponse(response.getEntity());
    } catch (URISyntaxException use) {
        Log.w("MmsDownlader", use);
        throw new IOException("Bad URI syntax");
    }
}

From source file:org.wwscc.registration.attendance.Attendance.java

/**
 * Retrieve the attendance report from the main host
 * @param host the hostname to retrieve from
 * @throws IOException /*from   www  .j  a  va  2s.c o m*/
 * @throws URISyntaxException 
 * @throws UnsupportedEncodingException 
 */
public static void getAttendance(String host) throws IOException, URISyntaxException {
    DefaultHttpClient httpclient = new DefaultHttpClient();
    HttpProtocolParams.setUserAgent(httpclient.getParams(), "Scorekeeper/2.0");

    MonitorProgressStream monitor = new MonitorProgressStream("Download Attendance");
    monitor.setProgress(1);
    monitor.setNote("Initialize");

    HttpPost request = new HttpPost(new URI("http", host, "/history/attendance", null));
    File temp = File.createTempFile("attendance", "tmp");
    monitor.setProgress(2);
    monitor.setNote("Connecting/Calcuation...");

    HttpEntity download = httpclient.execute(request).getEntity();
    monitor.setProgress(3);
    monitor.setNote("Downloading...");

    FileOutputStream todisk = new FileOutputStream(temp);
    monitor.setStream(todisk, download.getContentLength());
    download.writeTo(monitor);
    FileUtils.copyFile(temp, defaultfile);
}

From source file:com.wms.opensource.images3android.images3.ImageS3Service.java

public static int addImage(String baseUrl, String imagePlantId, String filePath) {
    File file = new File(filePath);
    try {/*  ww w .  ja va  2 s . co m*/
        HttpClient client = getClient();

        String url = baseUrl + imagePlantId + "/images";
        HttpPost httppost = new HttpPost(url);
        InputStreamEntity reqEntity = new InputStreamEntity(new FileInputStream(file), -1);
        reqEntity.setContentType("binary/octet-stream");
        reqEntity.setChunked(true);
        httppost.setEntity(reqEntity);
        HttpResponse response = client.execute(httppost);
        return response.getStatusLine().getStatusCode();
    } catch (Exception e) {
        return -1;
    }
}

From source file:com.continuuity.loom.TestHelper.java

public static SchedulableTask takeTask(String loomUrl, TakeTaskRequest request) throws Exception {
    HttpPost httpPost = new HttpPost(String.format("%s/v1/loom/tasks/take", loomUrl));
    httpPost.setEntity(new StringEntity(GSON.toJson(request)));

    CloseableHttpClient httpClient = HttpClients.createDefault();
    CloseableHttpResponse response = httpClient.execute(httpPost);
    try {/*  w ww.ja v  a2 s.  c om*/
        Assert.assertEquals(2, response.getStatusLine().getStatusCode() / 100);
        if (response.getEntity() == null) {
            return null;
        }
        return GSON.fromJson(EntityUtils.toString(response.getEntity()), SchedulableTask.class);
    } finally {
        response.close();
    }
}

From source file:net.locosoft.fold.neo4j.internal.Neo4jRestUtil.java

public static JsonObject doPostJson(String uri, JsonObject content) {
    try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) {
        HttpPost httpPost = new HttpPost(uri);
        httpPost.addHeader("Content-Type", "application/json");
        StringEntity stringEntity = new StringEntity(content.toString(), "UTF-8");
        httpPost.setEntity(stringEntity);
        CloseableHttpResponse response = httpClient.execute(httpPost);

        String bodyText = EntityUtils.toString(response.getEntity());
        JsonObject jsonObject = JsonObject.readFrom(bodyText);
        return jsonObject;
    } catch (Exception ex) {
        ex.printStackTrace();//from   w w w . jav a2 s  .  c  o m
    }
    return null;
}

From source file:org.eclipse.dirigible.cli.apis.ImportProjectAPI.java

public static void importProject(RequestConfig config, String url, InputStream in, String filename,
        Map<String, String> headers) throws IOException {
    CloseableHttpClient httpClient = HttpClients.createDefault();

    MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
    entityBuilder.addPart(PART_NAME, new InputStreamBody(in, filename));

    HttpPost postRequest = new HttpPost(url);
    postRequest.setEntity(entityBuilder.build());
    addHeaders(postRequest, headers);//from  www  . jav a 2  s  .c o m
    if (config != null) {
        postRequest.setConfig(config);
    }
    executeRequest(httpClient, postRequest);
}

From source file:org.eclipse.cbi.common.signing.Signer.java

public static void signFile(File source, File target, String signerUrl)
        throws IOException, MojoExecutionException {
    HttpClient client = HttpClientBuilder.create().build();
    HttpPost post = new HttpPost(signerUrl);

    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);

    builder.addPart("file", new FileBody(source));
    post.setEntity(builder.build());/*from www  . j av  a2s  . co  m*/

    HttpResponse response = client.execute(post);
    int statusCode = response.getStatusLine().getStatusCode();

    HttpEntity resEntity = response.getEntity();

    if (statusCode >= 200 && statusCode <= 299 && resEntity != null) {
        InputStream is = resEntity.getContent();
        try {
            FileUtils.copyStreamToFile(new RawInputStreamFacade(is), target);
        } finally {
            IOUtil.close(is);
        }
    } else if (statusCode >= 500 && statusCode <= 599) {
        InputStream is = resEntity.getContent();
        String message = IOUtil.toString(is, "UTF-8");
        throw new NoHttpResponseException("Server failed with " + message);
    } else {
        throw new MojoExecutionException("Signer replied " + response.getStatusLine());
    }
}

From source file:com.android.isoma.enc.ServerCommunicator.java

public static String executePost(ArrayList<NameValuePair> postParameters) {
    String ServerResponse = null;
    HttpClient httpClient = getHttpClient();

    ResponseHandler<String> response = new BasicResponseHandler();
    HttpPost request = new HttpPost(url);
    try {/*from  w w  w.  j a  v  a 2s .  c om*/
        request.setHeader("Content-Type", "application/x-www-form-urlencoded");

        request.setEntity(new UrlEncodedFormEntity(postParameters, HTTP.UTF_8));

        ServerResponse = httpClient.execute(request, response);

    } catch (UnsupportedEncodingException e) {

        e.printStackTrace();
    } catch (ClientProtocolException e) {

        e.printStackTrace();
    } catch (IOException e) {

        e.printStackTrace();
    }

    return ServerResponse;
}

From source file:appserver.grupo5.http.java

public static Response Request(Method method, String url, String content, String contentType) {
    Response response;//from  ww  w  . j  a v a  2s. com
    try {
        HttpClient client = new DefaultHttpClient();
        HttpUriRequest request;
        switch (method) {
        case GET:
            request = new HttpGet(url);
            break;
        case POST:
            request = new HttpPost(url);
            ((HttpPost) request).setEntity(new StringEntity(content));
            break;
        case PUT:
            request = new HttpPut(url);
            ((HttpPut) request).setEntity(new StringEntity(content));
            break;
        case DELETE:
            request = new HttpDeleteWithBody(url);
            ((HttpDeleteWithBody) request).setEntity(new StringEntity(content));
            break;
        default:
            request = new HttpGet(url);
            break;
        }
        if (method != Method.GET) {
            request.setHeader("Content-type", contentType);
        }
        response = executeRequest(client, request);
    } catch (Exception e) {
        response = Response.status(400).entity(e.getMessage()).build();
    }
    return response;
}

From source file:com.android.feedmeandroid.HTTPClient.java

public static ArrayList<JSONObject> SendHttpPost(String URL, JSONObject jsonObjSend) {

    try {/* www  .  ja  v  a2 s  .c o  m*/
        ArrayList<JSONObject> retArray = new ArrayList<JSONObject>();
        DefaultHttpClient httpclient = new DefaultHttpClient();
        HttpPost httpPostRequest = new HttpPost(URL);

        StringEntity se;
        se = new StringEntity(jsonObjSend.toString());

        // Set HTTP parameters
        httpPostRequest.setEntity(se);
        httpPostRequest.setHeader("Accepts", "application/json");
        httpPostRequest.setHeader("Content-Type", "application/json");
        // httpPostRequest.setHeader("Accept-Encoding", "gzip"); // only set
        // this parameter if you would like to use gzip compression

        long t = System.currentTimeMillis();
        HttpResponse response = (HttpResponse) httpclient.execute(httpPostRequest);
        Log.v(TAG, "HTTPResponse received in [" + (System.currentTimeMillis() - t) + "ms]");

        // Get hold of the response entity (-> the data):
        HttpEntity entity = response.getEntity();

        if (entity != null) {
            // Read the content stream
            InputStream instream = entity.getContent();
            Header contentEncoding = response.getFirstHeader("Content-Encoding");
            if (contentEncoding != null && contentEncoding.getValue().equalsIgnoreCase("gzip")) {
                instream = new GZIPInputStream(instream);
            }

            // convert content stream to a String
            String resultString = convertStreamToString(instream);
            Log.i(TAG, resultString);
            instream.close();
            resultString = resultString.substring(1, resultString.length() - 2); // remove wrapping "[" and
            // "]"
            String[] results = resultString.split("\\},\\{");
            for (int i = 0; i < results.length; i++) {
                JSONObject jsonObjRecv;
                String res = results[i];

                // Transform the String into a JSONObject
                if (i == 0 && results.length > 1) {
                    jsonObjRecv = new JSONObject(res + "}");
                } else if (i == results.length - 1 && results.length > 1) {
                    jsonObjRecv = new JSONObject("{" + res);
                } else {
                    jsonObjRecv = new JSONObject("{" + res + "}");
                }
                retArray.add(jsonObjRecv);

                // Raw DEBUG output of our received JSON object:
                Log.i(TAG, "<JSONObject>\n" + jsonObjRecv.toString() + "\n</JSONObject>");
            }

            return retArray;
        }

    } catch (Exception e) {
        // More about HTTP exception handling in another tutorial.
        // For now we just print the stack trace.
        e.printStackTrace();
    }
    return null;
}