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.cbtec.eliademyutils.EliademyUtils.java

public static String serviceCall(String data, String webService, String token, String serviceClient) {

    String retval = null;/*  ww w.ja  v a  2 s  .c  o m*/
    Log.d("EliademyUtils", "Service: " + data + " Service: " + webService);

    try {
        DefaultHttpClient httpclient = new DefaultHttpClient();
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();

        if (data.toString().length() > 0) {
            JSONObject jsObj = new JSONObject(data.toString());
            nameValuePairs.addAll(nameValueJson(jsObj, ""));
        }
        nameValuePairs.add(new BasicNameValuePair("wstoken", token));
        nameValuePairs.add(new BasicNameValuePair("wsfunction", webService));
        nameValuePairs.add(new BasicNameValuePair("moodlewsrestformat", "json"));

        HttpPost httppost = new HttpPost(serviceClient + "/webservice/rest/server.php?");

        Log.d("EliademyUtils", nameValuePairs.toString());
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

        HttpResponse response = httpclient.execute(httppost);
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            StringBuilder jsonStr = new StringBuilder();
            InputStream iStream = entity.getContent();
            BufferedReader bufferReader = new BufferedReader(new InputStreamReader(iStream));
            String jpart;
            while ((jpart = bufferReader.readLine()) != null) {
                jsonStr.append(jpart);
            }
            iStream.close();
            return jsonStr.toString();
        }
    } catch (Exception e) {
        Log.e("EliademyUtils", "exception", e);
        return retval;
    }
    return retval;
}

From source file:eu.eexcess.partnerdata.evaluation.enrichment.PartnerRecommenderEvaluationTestHelper.java

static public ResultList getRecommendations(String deploymentContext, int port, StringEntity params) {
    HttpClient httpClient = new DefaultHttpClient();
    ResultList resultList = null;/*w w w  .  j a  v  a2s .c  o m*/
    try {

        HttpPost request = new HttpPost(
                "http://localhost:" + port + "/" + deploymentContext + "/partner/recommend/");
        request.addHeader("content-type", "application/xml");
        request.setEntity(params);
        HttpResponse response = httpClient.execute(request);
        String responseString = EntityUtils.toString(response.getEntity());

        resultList = PartnerRecommenderEvaluationTestHelper.parseResponse(responseString);

    } catch (Exception ex) {
        System.out.println(ex);
    } finally {
        httpClient.getConnectionManager().shutdown();
    }
    return resultList;
}

From source file:app.wz.HttpClient.java

public static String SendHttpPost(String URL, JSONObject jsonObjSend) {

    try {//  w w w  .j a v  a2  s .c  o m
        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) {
            return EntityUtils.toString(entity);
            //            // 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();
            //            resultString = resultString.substring(1,resultString.length()-1); // remove wrapping "[" and "]"
            //
            //            // 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:com.ibm.xsp.xflow.activiti.util.HttpClientUtil.java

public static String post(String url, Cookie[] cookies, String content) {
    String body = null;/*from w ww. ja va 2s. c om*/
    try {
        StringBuffer buffer = new StringBuffer();
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost postRequest = new HttpPost(url);

        StringEntity input = new StringEntity(content);
        input.setContentType("application/json");
        postRequest.setEntity(input);

        httpClient.setCookieStore(new BasicCookieStore());
        String hostName = new URL(url).getHost();
        String domain = hostName.substring(hostName.indexOf("."));
        for (int i = 0; i < cookies.length; i++) {
            if (logger.isLoggable(Level.FINEST)) {
                logger.finest("Cookie:" + cookies[i].getName() + ":" + cookies[i].getValue() + ":"
                        + cookies[i].getDomain() + ":" + cookies[i].getPath());
            }
            BasicClientCookie cookie = new BasicClientCookie(cookies[i].getName(), cookies[i].getValue());
            cookie.setVersion(0);
            cookie.setDomain(domain);
            cookie.setPath("/");

            httpClient.getCookieStore().addCookie(cookie);
        }
        HttpResponse response = httpClient.execute(postRequest);
        BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent())));

        String output;
        if (logger.isLoggable(Level.FINEST)) {
            logger.finest("Output from Server .... \n");
        }
        while ((output = br.readLine()) != null) {
            if (logger.isLoggable(Level.FINEST)) {
                logger.finest(output);
            }
            buffer.append(output);
        }

        httpClient.getConnectionManager().shutdown();

        body = buffer.toString();

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

    return body;
}

From source file:com.example.montxu.magik_repair.HttpClient.java

public static JSONObject SendHttpPost(String URL, JSONObject jsonObjSend) {

    try {/*w  ww .j a  v  a  2 s. c  o  m*/
        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();
            //resultString = resultString.substring(1,resultString.length()-1); // remove wrapping "[" and "]"

            // 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:com.swetha.easypark.EasyParkHttpClient.java

/** 
 * @param url of the website and the post request
 * @return http response in string */
public static String executeHttpPost(String url, ArrayList<NameValuePair> postParameters) throws Exception {

    BufferedReader in = null;//from   ww w .j a  va  2 s  .c om

    try {

        HttpClient client = getHttpClient();

        HttpPost request = new HttpPost(url);

        UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(

                postParameters);

        request.setEntity(formEntity);
        Log.i("CustomHttpClient", "before sending request" + request);
        HttpResponse response = client.execute(request);
        Log.i("CustomHttpClient", "after sending request" + response.toString());
        //Log.i("CustomHttpClient", "after sending request response in to string" +response.getEntity().getContent().toString());

        in = new BufferedReader(new InputStreamReader(response.getEntity()

                .getContent()));

        StringBuffer sb = new StringBuffer("");

        String line = "";

        String NL = System.getProperty("line.separator");

        while ((line = in.readLine()) != null) {

            sb.append(line + NL);

        }

        in.close();

        String result = sb.toString();

        return result;

    }

    finally {

        if (in != null) {

            try {

                in.close();

            } catch (IOException e) {

                Log.e("log_tag", "Error converting result " + e.toString());

                e.printStackTrace();

            }

        }
    }

}

From source file:org.roda.core.util.RESTClientUtility.java

public static <T extends Serializable> T sendPostRequest(T element, Class<T> elementClass, String url,
        String resource, String username, String password) throws RODAException {
    CloseableHttpClient httpClient = HttpClientBuilder.create().build();
    String basicAuthToken = new String(Base64.encode((username + ":" + password).getBytes()));
    HttpPost httpPost = new HttpPost(url + resource);
    httpPost.setHeader("Authorization", "Basic " + basicAuthToken);
    httpPost.addHeader("content-type", "application/json");
    httpPost.addHeader("Accept", "application/json");

    try {//  w w  w.j a  va2  s.  c o  m
        httpPost.setEntity(new StringEntity(JsonUtils.getJsonFromObject(element)));
        HttpResponse response;
        response = httpClient.execute(httpPost);
        HttpEntity responseEntity = response.getEntity();

        int responseStatusCode = response.getStatusLine().getStatusCode();
        if (responseStatusCode == 201) {
            return JsonUtils.getObjectFromJson(responseEntity.getContent(), elementClass);
        } else {
            throw new RODAException("POST request response status code: " + responseStatusCode);
        }
    } catch (IOException e) {
        throw new RODAException("Error sending POST request", e);
    }
}

From source file:com.socioffice.grabmenu.model.JSONRequest.java

public static JSONObject SendHttpPost(String URL, JSONObject jsonObjSend) {

    try {//from  w  ww.  ja  v  a  2s .  c o  m
        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");

        // only set this parameter if you would like to use gzip compression
        httpPostRequest.setHeader("Accept-Encoding", "gzip");

        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();
            resultString = resultString.substring(1, resultString.length() - 1); // remove wrapping "[" and
            // "]"

            // 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:org.opencastproject.remotetest.util.CaptureUtils.java

public static void setState(String recordingId, String state) throws Exception {
    HttpPost request = new HttpPost(BASE_URL + "/capture-admin/recordings/" + recordingId);
    List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
    params.add(new BasicNameValuePair("state", state));
    request.setEntity(new UrlEncodedFormEntity(params));
    TrustedHttpClient client = Main.getClient();
    HttpResponse response = client.execute(request);
    if (HttpStatus.SC_OK != response.getStatusLine().getStatusCode())
        throw new IllegalStateException("Recording '" + recordingId + "' not found");
    Main.returnClient(client);/*from w w w. j  a  va2  s  . c  om*/
}

From source file:com.harshad.linconnectclient.NotificationUtilities.java

public static boolean sendData(Context c, Notification n, String packageName) {
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(c);

    ConnectivityManager connManager = (ConnectivityManager) c.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);

    // Check Wifi state, whether notifications are enabled globally, and
    // whether notifications are enabled for specific application
    if (prefs.getBoolean("pref_toggle", true) && prefs.getBoolean(packageName, true) && mWifi.isConnected()) {
        String ip = prefs.getString("pref_ip", "0.0.0.0:9090");

        // Magically extract text from notification
        ArrayList<String> notificationData = NotificationUtilities.getNotificationText(n);

        // Use PackageManager to get application name and icon
        final PackageManager pm = c.getPackageManager();
        ApplicationInfo ai;/* w ww.  j a  v a2s.  com*/
        try {
            ai = pm.getApplicationInfo(packageName, 0);
        } catch (final NameNotFoundException e) {
            ai = null;
        }

        String notificationBody = "";
        String notificationHeader = "";
        // Create header and body of notification
        if (notificationData.size() > 0) {
            notificationHeader = notificationData.get(0);
            if (notificationData.size() > 1) {
                notificationBody = notificationData.get(1);
            }
        } else {
            return false;
        }

        for (int i = 2; i < notificationData.size(); i++) {
            notificationBody += "\n" + notificationData.get(i);
        }

        // Append application name to body
        if (pm.getApplicationLabel(ai) != null) {
            if (notificationBody.isEmpty()) {
                notificationBody = "via " + pm.getApplicationLabel(ai);
            } else {
                notificationBody += " (via " + pm.getApplicationLabel(ai) + ")";
            }
        }

        // Setup HTTP request
        MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

        // If the notification contains an icon, use it
        if (n.largeIcon != null) {
            entity.addPart("notificon",
                    new InputStreamBody(ImageUtilities.bitmapToInputStream(n.largeIcon), "drawable.png"));
        }
        // Otherwise, use the application's icon
        else {
            entity.addPart("notificon",
                    new InputStreamBody(
                            ImageUtilities.bitmapToInputStream(
                                    ImageUtilities.drawableToBitmap(pm.getApplicationIcon(ai))),
                            "drawable.png"));
        }

        HttpPost post = new HttpPost("http://" + ip + "/notif");
        post.setEntity(entity);

        try {
            post.addHeader("notifheader", Base64.encodeToString(notificationHeader.getBytes("UTF-8"),
                    Base64.URL_SAFE | Base64.NO_WRAP));
            post.addHeader("notifdescription", Base64.encodeToString(notificationBody.getBytes("UTF-8"),
                    Base64.URL_SAFE | Base64.NO_WRAP));
        } catch (UnsupportedEncodingException e) {
            post.addHeader("notifheader",
                    Base64.encodeToString(notificationHeader.getBytes(), Base64.URL_SAFE | Base64.NO_WRAP));
            post.addHeader("notifdescription",
                    Base64.encodeToString(notificationBody.getBytes(), Base64.URL_SAFE | Base64.NO_WRAP));
        }

        // Send HTTP request
        HttpClient client = new DefaultHttpClient();
        HttpResponse response;
        try {
            response = client.execute(post);
            String html = EntityUtils.toString(response.getEntity());
            if (html.contains("true")) {
                return true;
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
    return false;
}