Example usage for org.apache.http.client.methods HttpPost setEntity

List of usage examples for org.apache.http.client.methods HttpPost setEntity

Introduction

In this page you can find the example usage for org.apache.http.client.methods HttpPost setEntity.

Prototype

public void setEntity(final HttpEntity entity) 

Source Link

Usage

From source file:com.mirth.connect.client.core.ConnectServiceUtil.java

public static void registerUser(String serverId, String mirthVersion, User user, String[] protocols,
        String[] cipherSuites) throws ClientException {
    CloseableHttpClient httpClient = null;
    CloseableHttpResponse httpResponse = null;
    NameValuePair[] params = { new BasicNameValuePair("serverId", serverId),
            new BasicNameValuePair("version", mirthVersion),
            new BasicNameValuePair("user", ObjectXMLSerializer.getInstance().serialize(user)) };

    HttpPost post = new HttpPost();
    post.setURI(URI.create(URL_CONNECT_SERVER + URL_REGISTRATION_SERVLET));
    post.setEntity(new UrlEncodedFormEntity(Arrays.asList(params), Charset.forName("UTF-8")));
    RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(TIMEOUT)
            .setConnectionRequestTimeout(TIMEOUT).setSocketTimeout(TIMEOUT).build();

    try {/*from www  .  ja  va 2  s  .c  om*/
        HttpClientContext postContext = HttpClientContext.create();
        postContext.setRequestConfig(requestConfig);
        httpClient = getClient(protocols, cipherSuites);
        httpResponse = httpClient.execute(post, postContext);
        StatusLine statusLine = httpResponse.getStatusLine();
        int statusCode = statusLine.getStatusCode();
        if ((statusCode != HttpStatus.SC_OK) && (statusCode != HttpStatus.SC_MOVED_TEMPORARILY)) {
            throw new Exception("Failed to connect to update server: " + statusLine);
        }
    } catch (Exception e) {
        throw new ClientException(e);
    } finally {
        HttpClientUtils.closeQuietly(httpResponse);
        HttpClientUtils.closeQuietly(httpClient);
    }
}

From source file:com.ibm.devops.notification.MessageHandler.java

public static void postToWebhook(String webhook, boolean deployableMessage, JSONObject message,
        PrintStream printStream) {
    //check webhook
    if (Util.isNullOrEmpty(webhook)) {
        printStream.println("[IBM Cloud DevOps] IBM_CLOUD_DEVOPS_WEBHOOK_URL not set.");
        printStream.println("[IBM Cloud DevOps] Error: Failed to notify OTC.");
    } else {// w w w .j a  v a2s.co  m
        // set a 5 seconds timeout
        RequestConfig defaultRequestConfig = RequestConfig.custom().setSocketTimeout(5000)
                .setConnectTimeout(5000).setConnectionRequestTimeout(5000).build();
        CloseableHttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(defaultRequestConfig)
                .build();
        HttpPost postMethod = new HttpPost(webhook);
        try {
            StringEntity data = new StringEntity(message.toString());
            postMethod.setEntity(data);
            postMethod = Proxy.addProxyInformation(postMethod);
            postMethod.addHeader("Content-Type", "application/json");

            if (deployableMessage) {
                postMethod.addHeader("x-create-connection", "true");
                printStream.println("[IBM Cloud DevOps] Sending Deployable Mapping message to webhook:");
                printStream.println(message);
            }

            CloseableHttpResponse response = httpClient.execute(postMethod);

            if (response.getStatusLine().toString().matches(".*2([0-9]{2}).*")) {
                printStream.println("[IBM Cloud DevOps] Message successfully posted to webhook.");
            } else {
                printStream.println(
                        "[IBM Cloud DevOps] Message failed, response status: " + response.getStatusLine());
            }
        } catch (IOException e) {
            printStream.println("[IBM Cloud DevOps] IOException, could not post to webhook:");
            e.printStackTrace(printStream);
        }
    }
}

From source file:com.tedx.webservices.WebServices.java

public static JSONObject SendHttpPost(String URL, JSONObject jsonObjSend) {
    try {/*  w  w w  .j  a  v  a  2  s  .  c  om*/
        DefaultHttpClient httpclient = new DefaultHttpClient();
        HttpPost httpPostRequest = new HttpPost(URL);

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

        // Set HTTP parameters
        httpPostRequest.setEntity(se);
        httpPostRequest.setHeader("Accept", "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.i(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);
            instream.close();

            // remove wrapping "[" and "]"
            if (resultString.substring(0, 1).contains("["))
                resultString = resultString.substring(1, resultString.length() - 1);

            // Transform the String into a JSONObject
            JSONObject jsonObjRecv = new JSONObject(resultString);
            // Raw DEBUG output of our received JSON object:
            Log.i(TAG, "<jsonobject>\n" + jsonObjRecv.toString() + "\n</jsonobject>");

            return jsonObjRecv;
        }

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

From source file:fr.liglab.adele.cilia.workbench.restmonitoring.utils.http.HttpHelper.java

public static void post(PlatformID platformID, String path, String paramName, InputStream data)
        throws CiliaException {

    String url = getURL(platformID, path);

    HttpPost httppost = new HttpPost(url);

    MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

    InputStreamBody bin = new InputStreamBody(data, paramName);
    reqEntity.addPart(paramName, bin);// w  w w  . j a va2 s  .c  o  m

    httppost.setEntity(reqEntity);

    // HTTP request
    HttpClient httpClient = getClient();
    try {
        httpClient.execute(httppost, new BasicResponseHandler());
        httpClient.getConnectionManager().shutdown();
    } catch (Exception e) {
        httpClient.getConnectionManager().shutdown();
        throw new CiliaException("can't perform HTTP PUT request", e);
    }
}

From source file:cn.mrdear.pay.util.WebUtils.java

/**
 * POST/*from w w w  .j a va 2s  .c o  m*/
 *
 * @param url
 *            URL
 * @param inputStreamEntity
 *            
 * @return 
 */
public static String post(String url, InputStreamEntity inputStreamEntity) {

    String result = null;
    try {
        HttpPost httpPost = new HttpPost(url);
        inputStreamEntity.setContentEncoding("UTF-8");
        httpPost.setEntity(inputStreamEntity);
        CloseableHttpResponse httpResponse = HTTP_CLIENT.execute(httpPost);
        result = consumeResponse(httpResponse);
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException(e.getMessage(), e);
    } catch (ClientProtocolException e) {
        throw new RuntimeException(e.getMessage(), e);
    } catch (ParseException e) {
        throw new RuntimeException(e.getMessage(), e);
    } catch (IOException e) {
        throw new RuntimeException(e.getMessage(), e);
    }
    return result;
}

From source file:wvw.utils.pc.HttpHelper.java

public static String post(String url, JSONArray headers, String data) {
    HttpPost httpPost = new HttpPost(url);

    for (int i = 0; i < headers.length(); i++) {
        JSONArray header = headers.getJSONArray(i);

        httpPost.addHeader(header.getString(0), header.getString(1));
    }//from  w w w  .j a  va  2 s  .com

    String ret = null;
    try {
        httpPost.setEntity(new StringEntity(data));

        HttpClient httpClient = new DefaultHttpClient();
        HttpResponse response = httpClient.execute(httpPost);

        StatusLine status = response.getStatusLine();

        switch (status.getStatusCode()) {

        case 200:
            ret = IOUtils.readFromStream(response.getEntity().getContent());

            break;

        default:
            ret = genError(status.getReasonPhrase());

            break;
        }

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

        ret = genError(e.getClass() + ": " + e.getMessage());
    }

    return ret;
}

From source file:fr.shywim.antoinedaniel.utils.GcmUtils.java

public static void sendRegistrationIdToBackend(Context context, String regid, int version) {
    try {/*from   ww w. j av  a2s.  c om*/
        HttpPost post = new HttpPost(context.getString(R.string.api_register));
        List<NameValuePair> params = new ArrayList<>(2);
        params.add(new BasicNameValuePair("regid", regid));
        params.add(new BasicNameValuePair("version", Integer.toString(version)));
        post.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));

        HttpClient client = new DefaultHttpClient();
        HttpResponse response = client.execute(post);

        int responseCode = response.getStatusLine().getStatusCode();
        if (responseCode == 200 || responseCode == 201) {
            context.getSharedPreferences(AppConstants.GOOGLE_PREFS, Context.MODE_PRIVATE).edit()
                    .putBoolean(AppConstants.GOOGLE_GCM_REGISTERED, true).apply();
        }
    } catch (IOException e) {
        Crashlytics.logException(e);
    }
}

From source file:lib.pusher.Pusher.java

/**
 * Delivers a message to the Pusher API/*ww w . jav a 2  s. c  o  m*/
 * @param channel
 * @param event
 * @param jsonData
 * @param socketId
 * @return
 * @throws IOException
 * @throws ClientProtocolException
 */
public static String triggerPush(String channel, String event, String jsonData, String socketId)
        throws ClientProtocolException, IOException {
    //Build URI path
    String uriPath = buildURIPath(channel);
    //Build query
    String query = buildQuery(event, jsonData, socketId);
    //Generate signature
    String signature = buildAuthenticationSignature(uriPath, query);
    //Build URI
    String url = buildURI(uriPath, query, signature);

    DefaultHttpClient httpClient = new DefaultHttpClient();
    HttpContext cntxt = new BasicHttpContext();

    HttpPost httpPost = new HttpPost(url);
    httpPost.addHeader("Content-Type", "application/json");
    httpPost.setEntity(new StringEntity(jsonData, "UTF-8"));
    org.apache.http.HttpResponse httpResponse = httpClient.execute(httpPost);

    //Start request
    try {
        return EntityUtils.toString(httpResponse.getEntity());
    } catch (IOException e) {
        return null;
    }
}

From source file:xj.property.ums.common.NetworkUitlity.java

public static MyMessage post(String url, String data) {
    // TODO Auto-generated method stub
    CommonUtil.printLog("ums", url);
    String returnContent = "";
    MyMessage message = new MyMessage();
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost(url);
    try {/*from w ww .ja  v  a  2  s. c o m*/
        StringEntity se = new StringEntity(data, HTTP.UTF_8);
        CommonUtil.printLog("postdata", "content=" + data);
        se.setContentType("application/x-www-form-urlencoded");
        httppost.setEntity(se);
        HttpResponse response = httpclient.execute(httppost);
        int status = response.getStatusLine().getStatusCode();
        CommonUtil.printLog("ums", status + "");
        String returnXML = EntityUtils.toString(response.getEntity());
        returnContent = URLDecoder.decode(returnXML);
        switch (status) {
        case 200:
            message.setFlag(true);
            message.setMsg(returnContent);
            break;

        default:
            Log.e("error", status + returnContent);
            message.setFlag(false);
            message.setMsg(returnContent);
            break;
        }
    } catch (Exception e) {
        JSONObject jsonObject = new JSONObject();

        try {
            jsonObject.put("err", e.toString());
            returnContent = jsonObject.toString();
            message.setFlag(false);
            message.setMsg(returnContent);
        } catch (JSONException e1) {
            e1.printStackTrace();
        }

    }
    CommonUtil.printLog("UMSAGENT", message.getMsg());
    return message;
}

From source file:com.base.httpclient.HttpJsonClient.java

/**
 * post//from w ww  . jav  a  2  s .c  o  m
 * 
 * @param url
 *            URL
 * @param data
 *            
 * @return 
 * @throws ClientProtocolException
 * @throws IOException
 */
public static String post(String url, String data) throws ClientProtocolException, IOException {
    HttpClient httpclient = new DefaultHttpClient();
    try {
        HttpPost httpPost = new HttpPost(url);

        if (data != null) {
            ByteArrayEntity mult = new ByteArrayEntity(data.getBytes("UTF-8"));
            httpPost.setEntity(mult);
        }

        log.debug("begin to post url:" + url);
        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        return httpclient.execute(httpPost, responseHandler);
    } finally {
        httpclient.getConnectionManager().shutdown();
    }
}