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.apm4all.tracy.TracyCloseableHttpClientPublisher.java

@Override
public boolean publish(String tracySegment) {
    boolean published = false;
    if (null != this.uri) {
        CloseableHttpResponse response;//from w w w .j  a  va  2s . c  om
        // TODO: Externalize configuration
        HttpPost httpPost = new HttpPost(uri);
        StringEntity se;

        try {
            se = new StringEntity(tracySegment, StandardCharsets.UTF_8);
            se.setContentType(MediaType.APPLICATION_JSON);
            httpPost.setEntity(se);
            httpPost.setHeader(HttpHeaders.CONTENT_TYPE, TRACY_CONTENT_TYPE);
            response = httpClient.execute(httpPost);
            if (debug) {
                System.out.println(extractPostResponse(response));
            }
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                published = true;
            }
            response.close();
        } catch (Exception e) {
        }
    }
    return published;
}

From source file:retsys.client.http.HttpHelper.java

public HttpPost getHttpPostObj(String operation, String body) throws IOException {
    HttpPost post = null;//  ww w.j av  a2 s  .  c o  m

    post = new HttpPost(getHttpUrl(hostName, hostPort, context) + "/" + operation);

    StringEntity se = new StringEntity(body);
    se.setContentEncoding("UTF-8");
    se.setContentType("application/json");

    post.setEntity(se);

    return post;
}

From source file:retsys.client.http.HttpHelper.java

public HttpPut getHttpPutObj(String operation, String body) throws IOException {
    HttpPut put = null;//w ww. ja v  a  2  s . c  om

    put = new HttpPut(getHttpUrl(hostName, hostPort, context) + "/" + operation);

    StringEntity se = new StringEntity(body);
    se.setContentEncoding("UTF-8");
    se.setContentType("application/json");

    put.setEntity(se);

    return put;
}

From source file:com.wso2telco.gsma.authenticators.sms.SendSMS.java

/**
 * Post request./*from   w  w w. j a  va2 s  . c  om*/
 *
 * @param url        the url
 * @param requestStr the request str
 * @param operator   the operator
 * @throws IOException Signals that an I/O exception has occurred.
 */
protected void postRequest(String url, String requestStr, String operator, BasicFutureCallback futureCallback)
        throws IOException {

    //        HttpClient client = HttpClientBuilder.create().build();
    HttpClient client = new DefaultHttpClient();
    HttpPost postRequest = new HttpPost(url);

    postRequest.addHeader("accept", "application/json");
    postRequest.addHeader("Authorization", "Bearer " + smsConfig.getAuthToken());

    if (operator != null) {
        postRequest.addHeader("operator", operator);
    }

    StringEntity input = new StringEntity(requestStr);
    input.setContentType("application/json");

    postRequest.setEntity(input);

    Util.sendAsyncRequest(postRequest, futureCallback);
}

From source file:emcewen.websms.services.C2DMRegistrationService.java

private void registerForPush(String regID, String username) {
    Log.d(TAG, "Register with WebApp!");
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost("http://sms.evanmcewen.ca/devices");
    JSONObject json = new JSONObject();
    TelephonyManager telephonyManager = (TelephonyManager) this.getSystemService(TELEPHONY_SERVICE);

    try {//from  www  .j  a va  2 s. c om
        // Add your data
        json.put("username", username);
        json.put("reg_id", regID);
        json.put("device_id", telephonyManager.getDeviceId());
        json.put("nickname", "");
        StringEntity se = new StringEntity(json.toString());
        se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
        httppost.setEntity(se);

        // Execute HTTP Post Request
        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        String response = httpclient.execute(httppost, responseHandler);

        if (response != null) {
            Intent successIntent = new Intent(WebSMSActivity.PUSH_SUCCESS);
            super.sendBroadcast(successIntent);
        }
    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
    } catch (IOException e) {
        // TODO Auto-generated catch block
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:org.bishoph.oxdemo.util.CreateTaskAction.java

@Override
protected JSONObject doInBackground(Object... params) {
    try {//from  w  w  w  . j  av  a2  s  .co  m
        String uri = (String) params[0];
        String title = (String) params[1];
        if (title == null && folder_id > 0) {
            Log.v("OXDemo", "Either title or folder_id missing. Done nothing!");
            return null;
        }

        Log.v("OXDemo", "Attempting to create task " + title + " on " + uri);

        JSONObject jsonobject = new JSONObject();
        jsonobject.put("folder_id", folder_id);
        jsonobject.put("title", title);
        jsonobject.put("status", 1);
        jsonobject.put("priority", 0);
        jsonobject.put("percent_completed", 0);
        jsonobject.put("recurrence_type", 0);
        jsonobject.put("private_flag", false);
        jsonobject.put("notification", false);

        Log.v("OXDemo", "Body = " + jsonobject.toString());
        HttpPut httpput = new HttpPut(uri);
        StringEntity stringentity = new StringEntity(jsonobject.toString(), HTTP.UTF_8);
        stringentity.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json;charset=UTF-8"));
        httpput.setHeader("Accept", "application/json, text/javascript");
        httpput.setHeader("Content-type", "application/json");
        httpput.setEntity(stringentity);

        HttpResponse response = httpclient.execute(httpput, localcontext);
        Log.v("OXDemo", "Created task " + title);
        HttpEntity entity = response.getEntity();
        String result = EntityUtils.toString(entity);
        Log.d("OXDemo", "<<<<<<<\n" + result + "\n\n");
        JSONObject jsonObj = new JSONObject(result);
        jsonObj.put("title", title);
        return jsonObj;
    } catch (JSONException e) {
        Log.e("OXDemo", e.getMessage());
    } catch (IOException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

From source file:com.peopleapi.RegisterWithApi.java

@Override
protected String doInBackground(String... params) {
    //the result from the api or errors go into this string
    String fromApiString = "";

    DefaultHttpClient client = (DefaultHttpClient) getNewHttpClient();
    HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000); // Timeout Limit
    HttpResponse response;//from  w w w.ja  va  2  s .  c o  m
    JSONObject json = new JSONObject();
    try {

        HttpPost post = new HttpPost(context.getResources().getString(R.string.api_registerurl));
        json.put("username", params[0]);
        json.put("password", params[1]);
        json.put("confirmPassword", params[2]);

        StringEntity se = new StringEntity(json.toString());
        se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
        post.setEntity(se);
        response = client.execute(post);
        int code = response.getStatusLine().getStatusCode();
        //We have to go back and get the token and user data...

        /* Checking response */
        if (response != null) {
            InputStream inputStream = response.getEntity().getContent();
            // Get the entity data here
            if (inputStream != null) {
                ByteArrayOutputStream content = new ByteArrayOutputStream();
                int readBytes = 0;
                byte[] sBuffer = new byte[512];
                while ((readBytes = inputStream.read(sBuffer)) != -1) {
                    content.write(sBuffer, 0, readBytes);
                }
                fromApiString = new String(content.toByteArray()) + code;
                inputStream.close();
            }
        }

    } catch (Exception e) {

        fromApiString = e.getMessage().toString();
    }
    return fromApiString;
}

From source file:WSpatern.LoginWS.java

public void getLoginAuth(String user, String password) {
    try {/*w  w w.  j a v a  2 s .c  o  m*/
        DefaultHttpClient client = new DefaultHttpClient();
        HttpPut putRequest = new HttpPut("https://documenta-dms.com/DMSWS/api/v1/login/");

        StringEntity input = new StringEntity("<user>\n" + "<username>" + user + "</username>\n" + "<password>"
                + password + "</password>\n" + "</user>");
        input.setContentType("application/xml");
        System.out.println("Out Put Of WS " + input);
        putRequest.setEntity(input);
        HttpResponse response = client.execute(putRequest);
        BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
        String line = null;
        while ((line = rd.readLine()) != null) {

            System.out.println(line);
            if (!line.contains("<html>")) {
                parseXML(line);
            } else {
                valid = false;
            }

        }
    } catch (UnsupportedEncodingException ex) {
        Logger.getLogger(LoginWS.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(LoginWS.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:org.fcrepo.storage.policy.FedoraStoragePolicyIT.java

@Test
public void testInvalidPoliciesCreateByPost() throws Exception {
    final HttpPost objMethod = HttpPostObjMethod(POLICY_RESOURCE);
    StringEntity input = new StringEntity("mix:newType " + MIME + " " + STORE, "UTF-8");
    input.setContentType(APPLICATION_FORM_URLENCODED);
    objMethod.setEntity(input);/*from   w  w  w . j a  v a2  s .co  m*/
    final HttpResponse response = client.execute(objMethod);
    assertEquals(response.getStatusLine().getStatusCode(), 500);
}

From source file:net.dataninja.oracle.client.DataNinjaHttpClient.java

public String fetchSmartSentimentRdf(String text, String url, int maxSize) {
    String output = "";
    try {/*from   www  .j  a v  a 2s .co  m*/

        HttpClient client = getHttpClient();

        HttpPost postRequest = new HttpPost(config.getApiUrl() + "/smartsentiment/tagentityrdf");

        DataNinjaInput dataNinjaInput = new DataNinjaInput();
        dataNinjaInput.setText(text);
        dataNinjaInput.setUrl(url);
        dataNinjaInput.setMax_size(maxSize);
        System.out.println(dataNinjaInput.toJsonString());

        StringEntity entity = new StringEntity(dataNinjaInput.toJsonString());
        entity.setContentType("application/json");
        postRequest.setEntity(entity);

        // Add additional header to postRequest which accepts application/json data
        postRequest.addHeader("accept", "application/json");
        postRequest.addHeader("X-Mashape-Key", config.getMashapeKey());

        System.out.println(postRequest.toString());

        // Execute the POST request and catch response
        HttpResponse response = client.execute(postRequest);

        // Check for HTTP response code: 200 = success
        if (response.getStatusLine().getStatusCode() != 200) {
            System.out.printf(response.toString());
            throw new RuntimeException(
                    "Failed : HTTP error code : " + response.getStatusLine().getStatusCode());
        }

        // Get-Capture Complete the RDF body response
        BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent())));
        StringBuffer sb = new StringBuffer();
        String line;

        // Simply iterate through RDF response and show on console.
        while ((line = br.readLine()) != null) {
            sb.append(line).append("\n");
            // System.out.println(line);
        }
        output = sb.toString();

    } catch (ClientProtocolException e) {
        System.out.println("Problem fetching RDF content");
        e.printStackTrace();
    } catch (IOException e) {
        System.out.println("Problem fetching RDF content");
        e.printStackTrace();
    } catch (UnrecoverableKeyException e) {
        System.out.println("Problem fetching RDF content");
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        System.out.println("Problem fetching RDF content");
        e.printStackTrace();
    } catch (KeyStoreException e) {
        System.out.println("Problem fetching RDF content");
        e.printStackTrace();
    } catch (KeyManagementException e) {
        System.out.println("Problem fetching RDF content");
        e.printStackTrace();
    }
    return output;
}