Example usage for org.apache.http.entity StringEntity setContentType

List of usage examples for org.apache.http.entity StringEntity setContentType

Introduction

In this page you can find the example usage for org.apache.http.entity StringEntity setContentType.

Prototype

public void setContentType(Header header) 

Source Link

Usage

From source file:com.bright.json.JSonRequestor.java

public static List<Cookie> doLogin(String user, String pass, String myURL) {
    try {//from w  w  w. jav a 2  s  . c o  m
        cmLogin loginReq = new cmLogin("login", user, pass);

        GsonBuilder builder = new GsonBuilder();

        Gson g = builder.create();
        String json = g.toJson(loginReq);

        /* HttpClient httpclient = new DefaultHttpClient(); */

        HttpClient httpclient = getNewHttpClient();
        CookieStore cookieStore = new BasicCookieStore();

        HttpContext localContext = new BasicHttpContext();
        localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);

        /* httpclient = WebClientDevWrapper.wrapClient(httpclient); */

        httpclient.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY);
        HttpParams params = httpclient.getParams();
        HttpConnectionParams.setConnectionTimeout(params, 1000);
        HttpConnectionParams.setSoTimeout(params, 1000);
        HttpPost httppost = new HttpPost(myURL);
        StringEntity stringEntity = new StringEntity(json);
        stringEntity.setContentType("application/json");
        httppost.setEntity(stringEntity);

        System.out.println("executing request " + httppost.getRequestLine());
        HttpResponse response = httpclient.execute(httppost, localContext);

        System.out.println(response + "\n");
        for (Cookie c : ((AbstractHttpClient) httpclient).getCookieStore().getCookies()) {
            System.out.println("\n Cookie: " + c.toString() + "\n");
        }

        List<Cookie> cookies = cookieStore.getCookies();
        for (int i = 0; i < cookies.size(); i++) {
            System.out.println("Local cookie: " + cookies.get(i));
        }

        HttpEntity resEntity = response.getEntity();

        System.out.println("----------------------------------------");
        System.out.println(response.getStatusLine());
        if (resEntity != null) {
            System.out.println("Response content length: " + resEntity.getContentLength());
            System.out.println("Chunked?: " + resEntity.isChunked());
            String message = new String(EntityUtils.toString(resEntity));
            System.out.println(message);
            return cookies;
        }
        EntityUtils.consume(resEntity);

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

    return null;

}

From source file:es.ucm.look.data.remote.restful.RestMethod.java

/**
 * Used to insert an element/*  w w w  . j  a  v  a2 s . com*/
 * 
 * @param url
 *       Element URI
 * @param c
 *       The element represented with a JSON
 * @return
 *       The response
 */
public static HttpResponse doPost(String url, JSONObject c) {
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost request = new HttpPost(url);
    StringEntity s = null;
    try {
        s = new StringEntity(c.toString());
    } catch (UnsupportedEncodingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    s.setContentEncoding("UTF-8");
    s.setContentType("application/json");

    request.setEntity(s);
    request.addHeader("accept", "application/json");

    try {
        return httpclient.execute(request);
    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return null;
}

From source file:es.ucm.look.data.remote.restful.RestMethod.java

/**
 * To Update an element/*from w  ww .j  a  v a  2s. c om*/
 * 
 * @param url
 *       Element URI
 * @param c
 *       The element to update represented with a JSON
 * @return
 *       The response
 */
public static HttpResponse doPut(String url, JSONObject c) {
    HttpClient httpclient = new DefaultHttpClient();
    HttpPut request = new HttpPut(url);
    StringEntity s = null;
    try {
        s = new StringEntity(c.toString());
    } catch (UnsupportedEncodingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    s.setContentEncoding("UTF-8");
    s.setContentType("application/json");

    request.setEntity(s);
    request.addHeader("accept", "application/json");

    try {
        return httpclient.execute(request);
    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return null;

}

From source file:com.optimusinfo.elasticpath.cortex.common.Utils.java

public static int putRequest(String deleteUrl, JSONObject requestBody, String accessToken, String contentType,
        String contentTypeString, String authorizationString, String accessTokenInitializer) {
    // Making HTTP request
    try {/*w ww . j  a v  a2  s. co m*/
        DefaultHttpClient httpClient = new DefaultHttpClient();
        Log.i("PUT REQUEST", deleteUrl);
        HttpPut httpPut = new HttpPut(deleteUrl);
        httpPut.setHeader(contentTypeString, contentType);
        httpPut.setHeader(authorizationString, accessTokenInitializer + " " + accessToken);

        if (requestBody != null) {
            StringEntity requestEntity = new StringEntity(requestBody.toString());
            requestEntity.setContentEncoding("UTF-8");
            requestEntity.setContentType(contentType);
            httpPut.setEntity(requestEntity);
        }

        HttpResponse httpResponse = httpClient.execute(httpPut);
        return httpResponse.getStatusLine().getStatusCode();
    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return 0;
}

From source file:com.optimusinfo.elasticpath.cortex.common.Utils.java

/**
 * /*from w w  w .  j av  a 2  s . co m*/
 * @param accessToken
 * @param postURL
 * @param ent
 * @param contentType
 * @return
 */
public static int postData(String postUrl, JSONObject requestBody, String accessToken, String contentType,
        String accessTokenInitializer) {
    HttpClient client = new DefaultHttpClient();
    try {

        HttpPost postRequest = new HttpPost(postUrl);
        postRequest.setHeader(Constants.RequestHeaders.CONTENT_TYPE_STRING, contentType);
        postRequest.setHeader(Constants.RequestHeaders.AUTHORIZATION_STRING,
                accessTokenInitializer + " " + accessToken);

        if (requestBody != null) {
            StringEntity requestEntity = new StringEntity(requestBody.toString());
            requestEntity.setContentEncoding("UTF-8");
            requestEntity.setContentType(contentType);
            postRequest.setEntity(requestEntity);
        }

        HttpResponse responsePOST = client.execute(postRequest);
        Log.i("POST RESPONSE", EntityUtils.toString(responsePOST.getEntity()));

        return responsePOST.getStatusLine().getStatusCode();

    } catch (IOException e) {
        e.printStackTrace();
    } catch (NullPointerException e) {
        e.printStackTrace();
    } finally {
        client.getConnectionManager().shutdown();
    }
    return 0;
}

From source file:azureml_besapp.AzureML_BESApp.java

/**
 * Call REST API to submit job to Azure ML for batch predictions
 * @return response from the REST API//from  w  w w .  java2 s .c om
 */
public static String besHttpPost() {

    HttpPost post;
    HttpClient client;
    StringEntity entity;

    try {
        // create HttpPost and HttpClient object
        post = new HttpPost(apiurl);
        client = HttpClientBuilder.create().build();

        // setup output message by copying JSON body into 
        // apache StringEntity object along with content type
        entity = new StringEntity(jsonBody, HTTP.UTF_8);
        entity.setContentEncoding(HTTP.UTF_8);
        entity.setContentType("text/json");

        // add HTTP headers
        post.setHeader("Accept", "text/json");
        post.setHeader("Accept-Charset", "UTF-8");

        // set Authorization header based on the API key
        post.setHeader("Authorization", ("Bearer " + apikey));
        post.setEntity(entity);

        // Call REST API and retrieve response content
        HttpResponse authResponse = client.execute(post);

        jobId = EntityUtils.toString(authResponse.getEntity()).replaceAll("\"", "");

        return jobId;

    } catch (Exception e) {

        return e.toString();
    }

}

From source file:password.pwm.http.servlet.oauth.OAuthConsumerServlet.java

private static RestResults makeHttpRequest(final PwmRequest pwmRequest, final String debugText,
        final OAuthSettings settings, final String requestUrl, final Map<String, String> requestParams)
        throws IOException, PwmUnrecoverableException {
    final Date startTime = new Date();
    final String requestBody = PwmURL.appendAndEncodeUrlParameters("", requestParams);
    LOGGER.trace(pwmRequest,//  w ww. j  a  v a  2  s  .c  o m
            "beginning " + debugText + " request to " + requestUrl + ", body: \n" + requestBody);
    final HttpPost httpPost = new HttpPost(requestUrl);
    httpPost.setHeader(PwmConstants.HttpHeader.Authorization.getHttpName(),
            new BasicAuthInfo(settings.getClientID(), settings.getSecret()).toAuthHeader());
    final StringEntity bodyEntity = new StringEntity(requestBody);
    bodyEntity.setContentType(PwmConstants.ContentTypeValue.form.getHeaderValue());
    httpPost.setEntity(bodyEntity);

    final X509Certificate[] certs = pwmRequest.getConfig()
            .readSettingAsCertificate(PwmSetting.OAUTH_ID_CERTIFICATE);

    final HttpResponse httpResponse;
    final String bodyResponse;
    try {
        if (certs == null || certs.length == 0) {
            httpResponse = PwmHttpClient.getHttpClient(pwmRequest.getConfig()).execute(httpPost);
        } else {
            httpResponse = PwmHttpClient
                    .getHttpClient(pwmRequest.getConfig(),
                            new PwmHttpClientConfiguration.Builder().setCertificate(certs).create())
                    .execute(httpPost);
        }
        bodyResponse = EntityUtils.toString(httpResponse.getEntity());
    } catch (PwmException | IOException e) {
        final String errorMsg;
        if (e instanceof PwmException) {
            errorMsg = "error during " + debugText + " http request to oauth server, remote error: "
                    + ((PwmException) e).getErrorInformation().toDebugStr();
        } else {
            errorMsg = "io error during " + debugText + " http request to oauth server: " + e.getMessage();
        }
        throw new PwmUnrecoverableException(new ErrorInformation(PwmError.ERROR_OAUTH_ERROR, errorMsg));
    }

    final StringBuilder debugOutput = new StringBuilder();
    debugOutput.append(debugText).append(TimeDuration.fromCurrent(startTime).asCompactString())
            .append(", status: ").append(httpResponse.getStatusLine()).append("\n");
    for (Header responseHeader : httpResponse.getAllHeaders()) {
        debugOutput.append(" response header: ").append(responseHeader.getName()).append(": ")
                .append(responseHeader.getValue()).append("\n");
    }

    debugOutput.append(" body:\n ").append(bodyResponse);

    if (httpResponse.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
        throw new PwmUnrecoverableException(new ErrorInformation(PwmError.ERROR_OAUTH_ERROR,
                "unexpected HTTP status code (" + httpResponse.getStatusLine().getStatusCode() + ") during "
                        + debugText + " request to " + requestUrl));
    }

    LOGGER.trace(pwmRequest, debugOutput.toString());
    return new RestResults(httpResponse, bodyResponse);
}

From source file:org.dasein.cloud.google.HttpsConnection.java

public static String getJSON(String iss, String p12File) throws Exception {
    System.out.println("ISS : " + iss);
    System.out.println("P12File : " + p12File);

    HttpClient client = new DefaultHttpClient();
    List formparams = new ArrayList();
    formparams.add(new BasicNameValuePair("grant_type", "urn:ietf:params:oauth:grant-type:jwt-bearer"));
    formparams.add(new BasicNameValuePair("assertion", GenerateToken.getToken(iss, p12File)));
    UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, "UTF-8");

    //      HttpClient client1 = new HttpClient();
    String url = "https://accounts.google.com/o/oauth2/token";
    //      System.out.println(url);
    //      PostMethod pm = new PostMethod(url); 
    //      pm.addRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    //      pm.addRequestHeader("Host", "accounts.google.com");
    ////      pm.addRequestHeader("Host", "accounts.google.com");
    //      pm.addParameter("grant_type", "urn:ietf:params:oauth:grant-type:jwt-bearer");
    //      pm.addParameter("assertion", GenerateToken.getData());
    ////      System.out.println(C.getData());
    ///*  w  w  w . jav a2  s .c  o  m*/
    //      int statusCode = client1.executeMethod(pm);

    HttpPost httppost = new HttpPost(url);
    httppost.addHeader("Content-Type", "application/x-www-form-urlencoded");
    httppost.setEntity(entity);
    HttpResponse httpResponse1 = client.execute(httppost);
    int s1 = httpResponse1.getStatusLine().getStatusCode();
    if (s1 == HttpStatus.SC_OK) {
        try {
            //   InputStream in = getResponseBody(pm);
            InputStream in = httpResponse1.getEntity().getContent();
            writeToFile(in, "D:\\google_out.txt");
            System.out.println(printFile("D:\\google_out.txt"));
        } catch (Exception e) {
            System.out.println("No response body !");
        }
    }

    JSONObject obj1 = new JSONObject(printFile("D:\\google_out.txt"));
    String access_token = obj1.getString("access_token");
    String token_type = obj1.getString("token_type");
    String expires_in = obj1.getString("expires_in");
    String resource = "instances";
    url = "https://www.googleapis.com/compute/v1beta14/projects/enstratus.com:enstratus-dev/zones/us-east1-a/"
            + resource + "?access_token=" + access_token + "&token_type=Bearer&expires_in=3600";
    String str = "{"
            + "\"image\": \"https://www.googleapis.com/compute/v1beta14/projects/google/global/images/gcel-10-04-v20130104\","
            + "\"machineType\": \"https://www.googleapis.com/compute/v1beta14/projects/enstratus.com:enstratus-dev/global/machineTypes/n1-standard-1\","
            + "\"name\": \"trial\","
            + "\"zone\": \"https://www.googleapis.com/compute/v1beta14/projects/enstratus.com:enstratus-dev/zones/us-east1-a/\","
            + "\"networkInterfaces\": [ {  \"network\": \"https://www.googleapis.com/compute/v1beta14/projects/enstratus.com:enstratus-dev/networks/default\" } ],"
            + "\"disks\": [ { \"type\": \"EPHEMERAL\",  \"deleteOnTerminate\": true  } ], \"metadata\": { \"items\": [ ],  \"kind\": \"compute#metadata\" }}";
    System.out.println(str);
    JSONObject json = new JSONObject(str);
    System.out.println("POST Methods : " + url);
    StringEntity se = new StringEntity(str);
    JSONObject json1 = new JSONObject();
    json1.put("image",
            "https://www.googleapis.com/compute/v1beta14/projects/google/global/images/gcel-10-04-v20130104");
    json1.put("machineType",
            "https://www.googleapis.com/compute/v1beta14/projects/enstratus.com:enstratus-dev/global/machineTypes/n1-standard-1");
    json1.put("name", "trial");
    json1.put("zone",
            "https://www.googleapis.com/compute/v1beta14/projects/enstratus.com:enstratus-dev/zones/us-east1-a/");
    //json1.put("image", "https://www.googleapis.com/compute/v1beta13/projects/google/images/ubuntu-10-04-v20120621");
    System.out.println(" JSON 1 : " + json.toString() + " \n JSON 2 : " + json1.toString());
    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
    nameValuePairs.add(new BasicNameValuePair("json", str));

    //              
    //               JSONObject jsonPayload = null;
    //               JSONObject obj = new JSONObject();
    //               
    //               try {
    //               obj.put("name", "vinotrial");
    //               obj.put("IPv4Range", "192.0.0.0/16");
    //               obj.put("description", "wrwer");
    //
    //               } catch (Exception e) {
    //                  
    //               }

    /*
    JSONObject jsonPayload = null;
    JSONObject obj = new JSONObject();
            
    try {
    obj.put("name", "testCreateStandardFirewall1734".toLowerCase());
    obj.put("description", "SSH allowed from anywhere");
    obj.put("network", "https://www.googleapis.com/compute/v1beta13/projects/enstratus.com:enstratus-dev/networks/default");
    JSONArray sranges = new JSONArray();
    JSONArray allowed = new JSONArray();
    JSONObject allowedtemp = new JSONObject();
    JSONArray ports = new JSONArray();
    allowedtemp.put("IPProtocol", "tcp");
    ports.put("22");
    allowedtemp.put("ports", ports);
    allowed.put(allowedtemp);
    //               
    //               JSONObject allowedtemp1 = new JSONObject();
    //               JSONArray ports1 = new JSONArray();
    //               allowedtemp1.put("IPProtocol", "udp");
    //               ports1.put("1-65535");
    //               allowedtemp1.put("ports", ports1);
    //               allowed.put(allowedtemp1);
    //               
    //               
    //               
    //               JSONObject allowedtemp2 = new JSONObject();
    //               
    //               allowedtemp2.put("IPProtocol", "icmp");
    //               
    //               allowed.put(allowedtemp2);
            
            
    sranges.put("0.0.0.0/0");
    obj.put("sourceRanges", sranges);
    obj.put("allowed", allowed);
    } catch (Exception e) {
             
    }
            
            
    */

    //UrlEncodedFormEntity entity1 = new UrlEncodedFormEntity(formparams1, "UTF-8");
    System.out.println("Creating an instance");
    HttpPost httppost1 = new HttpPost(url);
    httppost1.setHeader("Content-type", "application/json");
    //httppost1.addHeader("X-JavaScript-User-Agent", "trov");
    //httppost1.setEntity(se);
    //   httppost1.setEntity(new UrlEncodedFormEntity(nameValuePairs));

    System.out.println("payload:" + json1.toString());
    System.out.println("url:" + url);
    StringEntity se1 = new StringEntity(json1.toString());
    se1.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
    httppost1.setEntity(se1);
    //

    HttpClient base = new DefaultHttpClient();
    SSLContext ctx = SSLContext.getInstance("TLS");
    X509TrustManager tm = new X509TrustManager() {

        public void checkClientTrusted(X509Certificate[] xcs, String string) throws CertificateException {
        }

        public void checkServerTrusted(X509Certificate[] xcs, String string) throws CertificateException {
        }

        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }
    };
    ctx.init(null, new TrustManager[] { tm }, null);
    SSLSocketFactory ssf = new SSLSocketFactory(ctx);
    ssf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    ClientConnectionManager ccm = base.getConnectionManager();
    SchemeRegistry sr = ccm.getSchemeRegistry();
    sr.register(new Scheme("https", ssf, 443));
    HttpClient client1 = new DefaultHttpClient(ccm);

    //HttpClient client1 = new DefaultHttpClient();
    HttpResponse httpResponse2 = client1.execute(httppost1);
    int s2 = httpResponse2.getStatusLine().getStatusCode();
    if (s2 == HttpStatus.SC_OK) {
        try {
            //   InputStream in = getResponseBody(pm);
            InputStream in = httpResponse2.getEntity().getContent();
            writeToFile(in, "D:\\google_out.txt");
            System.out.println(printFile("D:\\google_out.txt"));
        } catch (Exception e) {
            System.out.println("No response body !");
        }
    } else {
        System.out.println("Instance creation failed with error status " + s2);
        InputStream in = httpResponse2.getEntity().getContent();
        writeToFile(in, "D:\\google_out.txt");
        System.out.println(printFile("D:\\google_out.txt"));
    }

    String[] Zone = { "europe-west1-a", "europe-west1-b", "us-central1-a", "us-central1-b", "us-central2-a",
            "us-east1-a" };
    for (String zone : Zone) {
        //             {
        HttpClient client3 = new DefaultHttpClient();
        resource = "instances";
        System.out.println("listing the instances !");
        //      url= "https://www.googleapis.com/compute/v1beta13/projects/google/kernels?access_token=" + access_token + "&token_type=Bearer&expires_in=3600" ;
        url = "https://www.googleapis.com/compute/v1beta14/projects/enstratus.com:enstratus-dev/zones/us-central1-a/"
                + resource + "?access_token=" + access_token + "&token_type=Bearer&expires_in=3600";
        //   url = "https://www.googleapis.com/compute/v1beta13/projects/enstratus.com:enstratus-dev?access_token=" + access_token + "&token_type=Bearer&expires_in=3600" ;
        //         url = "https://www.googleapis.com/compute/v1beta14/projects/enstratus.com:enstratus-dev/zones/us-east1-a/instances?access_token=" + access_token + "&token_type=Bearer&expires_in=3600" ;
        System.out.println("url : -----------" + url);

        JSONArray items = new JSONArray();

        HttpGet method = new HttpGet(url);

        HttpResponse httpResponse = client3.execute(method);
        int s = httpResponse.getStatusLine().getStatusCode();

        if (s == HttpStatus.SC_OK) {

            try {
                System.out.println("\nResponse from Server : ");
                //InputStream in = getResponseBody(gm);
                InputStream in = httpResponse.getEntity().getContent();
                writeToFile(in, "D:\\calendar_out.txt");
                String str1 = printFile("D:\\calendar_out.txt");
                System.out.println(str1);
                JSONObject jsonO = new JSONObject(str1);
                items = (JSONArray) jsonO.get("items");

                //   return printFile("D:\\calendar_out.txt");
            } catch (Exception e) {
                System.out.println("No response body !" + e.getLocalizedMessage());
            }

        } else
            System.out.println(httpResponse);

        for (int i = 0; i < items.length(); i++) {

            JSONObject item = (JSONObject) items.get(i);
            String name = null;
            if (item.has("name"))
                name = (String) item.get("name");
            //System.out.println("instance : " + name);

            if (!name.contains("default")) {
                System.out.println("Deleting the instance " + name);
                url = "https://www.googleapis.com/compute/v1beta14/projects/enstratus.com:enstratus-dev/zones/us-central1-a/"
                        + resource + "/" + name + "?access_token=" + access_token
                        + "&token_type=Bearer&expires_in=3600";
                System.out.println("url : " + url);

                HttpDelete delMethod = new HttpDelete(url);
                HttpResponse httpResponse3 = client.execute(delMethod);
                int s3 = httpResponse3.getStatusLine().getStatusCode();
                if (s3 == HttpStatus.SC_OK) {

                    try {
                        System.out.println("\nResponse from Server : ");
                        //InputStream in = getResponseBody(gm);
                        InputStream in = httpResponse3.getEntity().getContent();
                        writeToFile(in, "D:\\calendar_out.txt");
                        System.out.println(printFile("D:\\calendar_out.txt"));
                        //   return printFile("D:\\calendar_out.txt");
                    } catch (Exception e) {
                        System.out.println("No response body !");

                    }

                } else {
                    System.out.println("Deleting failed with status : " + s3);
                    try {
                        InputStream in = httpResponse3.getEntity().getContent();
                        writeToFile(in, "D:\\calendar_out.txt");
                        System.out.println(printFile("D:\\calendar_out.txt"));
                    } catch (Exception e) {

                    }
                }
            }
        }

        //      https://www.googleapis.com/compute/v1beta13/projects/enstratus.com%3Aenstratus-dev/instances/trial
        //      GetMethod gm      = new GetMethod(url); 
        //      HttpMethodParams params = new HttpMethodParams();
        ////      params.setParameter("calendarId", "vidhyanallasamy%40gmail.com");
        //      gm.setParams(params);
        //
        //      statusCode = client1.executeMethod(gm);
        //      System.out.println("\nStatus Code : " + statusCode);
        //
        //      try {
        //         System.out.println("\nResponse from Server : ");
        //         InputStream in = getResponseBody(gm);
        //         writeToFile(in, "D:\\calendar_out.txt");
        //         System.out.println(printFile("D:\\calendar_out.txt"));
        //      } catch (Exception e) {
        //         System.out.println("No response body !");
        //      }\
    }
    return null;
}

From source file:password.pwm.http.servlet.OAuthConsumerServlet.java

private static RestResults makeHttpRequest(final PwmRequest pwmRequest, final String debugText,
        final Settings settings, final String requestUrl, final Map<String, String> requestParams)
        throws IOException, PwmUnrecoverableException {
    final Date startTime = new Date();
    final String requestBody = ServletHelper.appendAndEncodeUrlParameters("", requestParams);
    LOGGER.trace(pwmRequest,/* w  w w  . jav  a2  s . c  o  m*/
            "beginning " + debugText + " request to " + requestUrl + ", body: \n" + requestBody);
    final HttpPost httpPost = new HttpPost(requestUrl);
    httpPost.setHeader(PwmConstants.HttpHeader.Authorization.getHttpName(),
            new BasicAuthInfo(settings.getClientID(), settings.getSecret()).toAuthHeader());
    final StringEntity bodyEntity = new StringEntity(requestBody);
    bodyEntity.setContentType(PwmConstants.ContentTypeValue.form.getHeaderValue());
    httpPost.setEntity(bodyEntity);

    final X509Certificate[] certs = pwmRequest.getConfig()
            .readSettingAsCertificate(PwmSetting.OAUTH_ID_CERTIFICATE);
    final HttpResponse httpResponse;
    if (certs == null || certs.length == 0) {
        httpResponse = PwmHttpClient.getHttpClient(pwmRequest.getConfig()).execute(httpPost);
    } else {
        httpResponse = PwmHttpClient
                .getHttpClient(pwmRequest.getConfig(), new PwmHttpClientConfiguration(certs)).execute(httpPost);
    }
    final String bodyResponse = EntityUtils.toString(httpResponse.getEntity());

    final StringBuilder debugOutput = new StringBuilder();
    debugOutput.append(debugText).append(TimeDuration.fromCurrent(startTime).asCompactString())
            .append(", status: ").append(httpResponse.getStatusLine()).append("\n");
    for (Header responseHeader : httpResponse.getAllHeaders()) {
        debugOutput.append(" response header: ").append(responseHeader.getName()).append(": ")
                .append(responseHeader.getValue()).append("\n");
    }

    debugOutput.append(" body:\n ").append(bodyResponse);
    LOGGER.trace(pwmRequest, debugOutput.toString());
    return new RestResults(httpResponse, bodyResponse);
}

From source file:org.structr.android.restclient.StructrObject.java

private static int store(String path, StructrObject entity, Type type) throws Throwable {

    AndroidHttpClient httpClient = getHttpClient();
    HttpPut httpPut = new HttpPut(path);
    HttpResponse response = null;/*from  w  w w.ja  va2 s .  c om*/
    Throwable throwable = null;
    int responseCode = 0;

    try {
        StringBuilder buf = new StringBuilder();
        gson.toJson(entity, type, buf);

        StringEntity body = new StringEntity(buf.toString());
        body.setContentType("application/json");
        httpPut.setEntity(body);
        configureRequest(httpPut);

        response = httpClient.execute(httpPut);
        responseCode = response.getStatusLine().getStatusCode();

    } catch (Throwable t) {
        throwable = t;
        httpPut.abort();
    } finally {
        if (response != null) {
            response.getEntity().consumeContent();
        }
    }

    if (throwable != null) {
        throw throwable;
    }

    return responseCode;
}