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.qcloud.CloudClient.java

public String post(String url, Map<String, String> header, Map<String, Object> body, byte[] data)
        throws UnsupportedEncodingException, IOException {
    HttpPost httpPost = new HttpPost(url);
    httpPost.setHeader("accept", "*/*");
    httpPost.setHeader("connection", "Keep-Alive");
    httpPost.setHeader("user-agent", "qcloud-java-sdk");
    if (header != null) {
        for (String key : header.keySet()) {
            httpPost.setHeader(key, header.get(key));
        }/*  w w  w  .  ja v  a2s  .  c  o  m*/
    }

    if (false == header.containsKey("Content-Type")
            || header.get("Content-Type").equals("multipart/form-data")) {
        MultipartEntity multipartEntity = new MultipartEntity();
        if (body != null) {
            for (String key : body.keySet()) {
                multipartEntity.addPart(key, new StringBody(body.get(key).toString()));
            }
        }

        if (data != null) {
            ContentBody contentBody = new ByteArrayBody(data, "qcloud");
            multipartEntity.addPart("fileContent", contentBody);
        }
        httpPost.setEntity(multipartEntity);
    } else {
        if (data != null) {
            String strBody = new String(data);
            StringEntity stringEntity = new StringEntity(strBody);
            httpPost.setEntity(stringEntity);
        }
    }

    //        HttpHost proxy = new HttpHost("127.0.0.1",8888);
    //        mClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY,proxy);

    HttpResponse httpResponse = mClient.execute(httpPost);
    int code = httpResponse.getStatusLine().getStatusCode();
    return EntityUtils.toString(httpResponse.getEntity(), "UTF-8");
}

From source file:ApkItem.java

public void uploadFile() {
    try {/* w ww  .  ja  v  a  2 s . c  o m*/
        CloseableHttpClient client = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost("http://192.168.1.130:8080/imooc/");

        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        builder.addBinaryBody(file.getName(), file, ContentType.APPLICATION_OCTET_STREAM, file.getName());
        HttpEntity multipart = builder.build();
        CountingMultipartRequestEntity.ProgressListener pListener = new CountingMultipartRequestEntity.ProgressListener() {
            @Override
            public void progress(float percentage) {
                apkState.setProcess((int) percentage);
                firePropertyChange("uploadProcess", -1, percentage);
            }
        };
        httpPost.setEntity(new CountingMultipartRequestEntity.ProgressEntityWrapper(multipart, pListener));
        CloseableHttpResponse response = client.execute(httpPost);
        client.close();
    } catch (IOException ex) {
        ex.printStackTrace();
    }
}

From source file:com.butler.service.PushNotifier.java

private void send() {
    try {/*  ww w .  j av a  2s .  co m*/
        String url = "https://android.googleapis.com/gcm/send";
        HttpClient client = new DefaultHttpClient();
        HttpPost request = new HttpPost(url);
        request.addHeader("Authorization", "key=AIzaSyCBODt7lH-oPSKiZJ5MJlugTS0BV3U-KGc");
        request.addHeader("Content-Type", "application/json");
        Header header = new Header();
        ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
        String rawData = ow.writeValueAsString(header);
        request.setEntity(new StringEntity(rawData));
        HttpResponse response = client.execute(request);
        // System.out.println("response"+IOUtils.toString(response.getEntity().getContent()));
    } catch (Exception ex) {
        Logger.getLogger(PushNotifier.class.getName()).log(Level.SEVERE, null, ex);
    }

}

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

public String sendRecord(String data, String srvName) {
    mode = false;/*from  ww  w.j  a  va2 s . c om*/
    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/" + srvName);

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

    }

    StringEntity se = null;

    try {
        se = new StringEntity(data);
    } 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.fcrepo.integration.api.FedoraIdentifiersIT.java

@Test
public void testGetNextPidResponds() throws Exception {
    final HttpPost method = new HttpPost(serverAddress + "nextPID");
    method.addHeader("Accepts", "text/xml");
    logger.debug("Executed testGetNextPidResponds()");
    assertEquals(HttpServletResponse.SC_OK, getStatus(method));
}

From source file:com.networknt.light.server.handler.loader.MenuLoader.java

private static void loadMenuFile(File file) {
    Scanner scan = null;/*w  w  w.j  a  v  a  2 s  .  c o m*/
    try {
        scan = new Scanner(file, Loader.encoding);
        // the content is only the data portion. convert to map
        String content = scan.useDelimiter("\\Z").next();
        HttpPost httpPost = new HttpPost("http://injector:8080/api/rs");
        StringEntity input = new StringEntity(content);
        input.setContentType("application/json");
        httpPost.setEntity(input);
        CloseableHttpResponse response = httpclient.execute(httpPost);

        try {
            System.out.println(response.getStatusLine());
            HttpEntity entity = response.getEntity();
            BufferedReader rd = new BufferedReader(new InputStreamReader(entity.getContent()));
            String json = "";
            String line = "";
            while ((line = rd.readLine()) != null) {
                json = json + line;
            }
            System.out.println("json = " + json);
            EntityUtils.consume(entity);
        } finally {
            response.close();
        }
    } catch (IOException ioe) {
        ioe.printStackTrace();
    } finally {
        if (scan != null)
            scan.close();
    }
}

From source file:com.drismo.logic.JsonFunctions.java

/**
 * Borrowed from:/*from   w  w  w. ja  v  a  2 s  .  com*/
 * http://p-xr.com/android-tutorial-how-to-parse-read-json-data-into-a-android-listview/
 * and slightly modified.
 * @param url the url to get JSON data from
 * @return the JSONObject containing all the info.
 */
public static JSONObject getJSONfromURL(String url) {
    //initialize
    InputStream is = null;
    String result = "";
    JSONObject jArray = null;
    //http post
    try {
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(url);
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity entity = response.getEntity();
        is = entity.getContent();
    } catch (Exception e) {
        Log.e("log_tag", "Error in http connection " + e.toString());
    }
    //convert response to string
    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(is), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        is.close();
        result = sb.toString();
    } catch (Exception e) {
        Log.e("log_tag", "Error converting result " + e.toString());
    }
    //try parse the string to a JSON object
    try {
        jArray = new JSONObject(result);
    } catch (JSONException e) {
        Log.e("log_tag", "Error parsing data " + e.toString());
    }
    return jArray;
}

From source file:com.google.resting.rest.client.BaseRESTClient.java

protected static HttpRequest buildHttpRequest(ServiceContext serviceContext) {

    String path = serviceContext.getPath();
    Verb verb = serviceContext.getVerb();
    HttpEntity httpEntity = serviceContext.getHttpEntity();
    List<Header> headers = serviceContext.getHeaders();

    if (verb == Verb.GET) {
        HttpGet httpGet = new HttpGet(path);
        if (headers != null) {
            for (Header header : headers)
                httpGet.addHeader(header);
        }/*from www .  j  ava2s . c o  m*/
        return httpGet;

    } else if (verb == Verb.POST) {
        HttpPost httpPost = new HttpPost(path);
        if (headers != null) {
            for (Header header : headers)
                httpPost.addHeader(header);
        }
        if (httpEntity != null)
            httpPost.setEntity(httpEntity);
        return httpPost;

    } else if (verb == Verb.DELETE) {
        HttpDelete httpDelete = new HttpDelete(path);
        if (headers != null) {
            for (Header header : headers)
                httpDelete.addHeader(header);
        }
        return httpDelete;

    } else {
        HttpPut httpPut = new HttpPut(path);
        if (headers != null) {
            for (Header header : headers)
                httpPut.addHeader(header);
        }
        if (httpEntity != null)
            httpPut.setEntity(httpEntity);
        return httpPut;
    } //if
}

From source file:org.jboss.arquillian.ce.httpclient.HttpClientBuilder.java

public static HttpRequest doPOST(String url) {
    return new HttpRequestImpl(new HttpPost(url));
}

From source file:ch.asadzia.cognitive.EmotionDetect.java

public ServiceResult process() {

    HttpClient httpclient = HttpClients.createDefault();

    try {/*from  ww  w. j  a  v  a 2s . co m*/
        URIBuilder builder = new URIBuilder("https://api.projectoxford.ai/emotion/v1.0/recognize");

        URI uri = builder.build();
        HttpPost request = new HttpPost(uri);
        request.setHeader("Content-Type", "application/octet-stream");
        request.setHeader("Ocp-Apim-Subscription-Key", apikey);

        // Request body
        FileEntity reqEntity = new FileEntity(imageData);
        request.setEntity(reqEntity);

        HttpResponse response = httpclient.execute(request);
        HttpEntity entity = response.getEntity();

        if (entity != null) {
            String responseStr = EntityUtils.toString(entity);

            if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
                System.err.println(responseStr);
                return null;
            }

            JSONArray jsonArray = (JSONArray) new JSONParser().parse(responseStr);
            JSONObject jsonObject = (JSONObject) jsonArray.get(0);

            HashMap<char[], Double> scores = (HashMap) jsonObject.get("scores");

            Map.Entry<char[], Double> maxEntry = null;

            for (Map.Entry<char[], Double> entry : scores.entrySet()) {
                System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());

                if (maxEntry == null || entry.getValue().compareTo(maxEntry.getValue()) > 0) {
                    maxEntry = entry;
                }
            }
            Object key = maxEntry.getKey();

            String winningEmotionName = (String) key;

            ServiceResult result = new ServiceResult(translateEmotion(winningEmotionName), winningEmotionName);

            System.out.println(responseStr);

            return result;
        }
    } catch (Exception e) {
        System.err.println(e.toString());
    }
    return null;
}