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.wso2telco.gsma.authenticators.saa.SmartPhoneAppAuthenticator.java

private void postDataToSaaServer(String url, StringEntity postData) throws SaaException, IOException {
    HttpClient httpClient = new DefaultHttpClient();
    HttpPost httpPost = new HttpPost(url);

    postData.setContentType("application/json");
    httpPost.setEntity(postData);// w w  w  .java  2 s .c  om

    HttpResponse httpResponse = httpClient.execute(httpPost);

    if (httpResponse.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
        log.error("SAA server replied with invalid HTTP status [ "
                + httpResponse.getStatusLine().getStatusCode() + "] ");

        throw new SaaException("Error occurred while posting data to SAA server");
    }
}

From source file:org.onosproject.protocol.http.ctl.HttpSBControllerImpl.java

@Override
public boolean patch(DeviceId device, String request, InputStream payload, String mediaType) {
    String type = typeOfMediaType(mediaType);

    try {//from w  ww. j a  v  a  2  s . c  o m
        log.debug("Url request {} ", getUrlString(device, request));
        HttpPatch httprequest = new HttpPatch(getUrlString(device, request));
        if (deviceMap.get(device).username() != null) {
            String pwd = deviceMap.get(device).password() == null ? ""
                    : COLON + deviceMap.get(device).password();
            String userPassword = deviceMap.get(device).username() + pwd;
            String base64string = Base64.getEncoder()
                    .encodeToString(userPassword.getBytes(StandardCharsets.UTF_8));
            httprequest.addHeader(AUTHORIZATION_PROPERTY, BASIC_AUTH_PREFIX + base64string);
        }
        if (payload != null) {
            StringEntity input = new StringEntity(IOUtils.toString(payload, StandardCharsets.UTF_8));
            input.setContentType(type);
            httprequest.setEntity(input);
        }
        CloseableHttpClient httpClient;
        if (deviceMap.containsKey(device) && deviceMap.get(device).protocol().equals(HTTPS)) {
            httpClient = getApacheSslBypassClient();
        } else {
            httpClient = HttpClients.createDefault();
        }
        int responseStatusCode = httpClient.execute(httprequest).getStatusLine().getStatusCode();
        return checkStatusCode(responseStatusCode);
    } catch (IOException | NoSuchAlgorithmException | KeyManagementException | KeyStoreException e) {
        log.error("Cannot do PATCH {} request on device {}", request, device, e);
    }
    return false;
}

From source file:com.layer.atlas.messenger.AtlasIdentityProvider.java

private String[] refreshContacts(boolean requestIdentityToken, String nonce, String userName) {
    try {//from   w w w .j  a  va2s. c o  m
        String url = "https://layer-identity-provider.herokuapp.com/apps/" + appId + "/atlas_identities";
        HttpPost post = new HttpPost(url);
        post.setHeader("Content-Type", "application/json");
        post.setHeader("Accept", "application/json");
        post.setHeader("X_LAYER_APP_ID", appId);

        JSONObject rootObject = new JSONObject();
        if (requestIdentityToken) {
            rootObject.put("nonce", nonce);
            rootObject.put("name", userName);
        } else {
            rootObject.put("name", "Web"); // name must be specified to make entiry valid
        }
        StringEntity entity = new StringEntity(rootObject.toString(), "UTF-8");
        entity.setContentType("application/json");
        post.setEntity(entity);

        HttpResponse response = (new DefaultHttpClient()).execute(post);
        if (HttpStatus.SC_OK != response.getStatusLine().getStatusCode()
                && HttpStatus.SC_CREATED != response.getStatusLine().getStatusCode()) {
            StringBuilder sb = new StringBuilder();
            sb.append("Got status ").append(response.getStatusLine().getStatusCode()).append(" [")
                    .append(response.getStatusLine()).append("] when logging in. Request: ").append(url);
            if (requestIdentityToken)
                sb.append(" login: ").append(userName).append(", nonce: ").append(nonce);
            Log.e(TAG, sb.toString());
            return new String[] { null, sb.toString() };
        }

        String responseString = EntityUtils.toString(response.getEntity());
        JSONObject jsonResp = new JSONObject(responseString);

        JSONArray atlasIdentities = jsonResp.getJSONArray("atlas_identities");
        List<Participant> participants = new ArrayList<Participant>(atlasIdentities.length());
        for (int i = 0; i < atlasIdentities.length(); i++) {
            JSONObject identity = atlasIdentities.getJSONObject(i);
            Participant participant = new Participant();
            participant.firstName = identity.getString("name");
            participant.userId = identity.getString("id");
            participants.add(participant);
        }
        if (participants.size() > 0) {
            setParticipants(participants);
            save();
            if (debug)
                Log.d(TAG, "refreshContacts() contacts: " + atlasIdentities);
        }

        if (requestIdentityToken) {
            String error = jsonResp.optString("error", null);
            String identityToken = jsonResp.optString("identity_token");
            return new String[] { identityToken, error };
        }
        return new String[] { null, "Refreshed " + participants.size() + " contacts" };
    } catch (Exception e) {
        Log.e(TAG, "Error when fetching identity token", e);
        return new String[] { null, "Cannot obtain identity token. " + e };
    }
}

From source file:org.couch4j.http.DatabaseImpl.java

public ServerResponse saveDocument(Object obj) {

    if (obj instanceof Document) {
        return this.saveDocument((Document) obj);
    }/* w ww  .  j  av  a  2 s  .c  o  m*/

    JSONObject json = JSONObject.fromObject(obj);
    try {
        StringEntity e = new StringEntity(json.toString(), UTF_8);
        e.setContentType("application/json");
        return client.post(urlResolver.baseUrl(), e);
    } catch (UnsupportedEncodingException e) {
        throw new AssertionError(e); // Should not happen as UTF-8 is
        // supported on every JVM
    }
}

From source file:com.shmsoft.dmass.data.index.SolrIndex.java

protected void sendPostCommand(String point, String param) throws SolrException {
    HttpClient httpClient = new DefaultHttpClient();

    try {//from w w w.j  av a2 s. c  om
        HttpPost request = new HttpPost(point);
        StringEntity params = new StringEntity(param, HTTP.UTF_8);
        params.setContentType("text/xml");

        request.setEntity(params);

        HttpResponse response = httpClient.execute(request);
        if (response.getStatusLine().getStatusCode() != 200) {
            History.appendToHistory("Solr Invalid Response: " + response.getStatusLine().getStatusCode());
        }

    } catch (Exception ex) {
        throw new SolrException("Problem sending request", ex);
    }
}

From source file:br.gov.frameworkdemoiselle.behave.integration.alm.ALMIntegration.java

public HttpResponse sendRequest(HttpClient client, String resource, String id, String xmlRequest)
        throws ClientProtocolException, IOException {
    String url = urlServer + "resources/" + projectAreaAlias + "/" + resource + "/" + id;

    log.debug(url);//from w ww. j a  va2 s.  c o m

    HttpPut request = new HttpPut(url);
    request.addHeader("Content-Type", "application/xml; charset=" + ENCODING);
    request.addHeader("Encoding", ENCODING);

    HttpParams params = request.getParams();
    params.setParameter(ClientPNames.HANDLE_REDIRECTS, Boolean.FALSE);

    // Seta o encoding da mensagem XML
    ContentType ct = ContentType.create("text/xml", ENCODING);

    StringEntity se = new StringEntity(xmlRequest, ct);
    se.setContentType("text/xml");
    se.setContentEncoding(ENCODING);
    request.setEntity(se);

    log.debug(xmlRequest);

    return client.execute(request);
}

From source file:requestToApi.java

public String send(StringEntity Input, String URL) {
    String output2 = "";
    try {//  w w  w .  j  a  v a  2 s . c om

        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost postRequest = new HttpPost(URL);

        StringEntity input = Input;

        input.setContentType("application/json");
        postRequest.setEntity(input);

        HttpResponse response = httpClient.execute(postRequest);

        if (response.getStatusLine().getStatusCode() != 200) {
            throw new RuntimeException(
                    "Failed : HTTP error code : " + response.getStatusLine().getStatusCode());
        }

        BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent())));

        String output;
        System.out.println("Output from Server .... \n");
        while ((output = br.readLine()) != null) {
            output2 = output;
            System.out.println(output);
        }

        httpClient.getConnectionManager().shutdown();

        return output2;

    } catch (MalformedURLException e) {

        e.printStackTrace();

    } catch (IOException e) {

        e.printStackTrace();

    }
    return output2;
}

From source file:org.envirocar.app.activity.RegisterFragment.java

public int createUser(String user, String token, String mail) {

    JSONObject requestJson = new JSONObject();
    try {/* www  .ja  va 2 s .  co  m*/
        requestJson.put("name", user);
        requestJson.put("token", token);
        requestJson.put("mail", mail);
    } catch (JSONException e) {
        logger.warn(e.getMessage(), e);
    }

    try {
        HttpPost postRequest = new HttpPost(ECApplication.BASE_URL + "/users");

        StringEntity input = new StringEntity(requestJson.toString(), HTTP.UTF_8);
        input.setContentType("application/json");

        postRequest.setEntity(input);
        return HTTPClient.execute(postRequest).getStatusLine().getStatusCode();

    } catch (UnsupportedEncodingException e) {
        // Shouldn't occur hopefully..
        logger.warn(e.getMessage(), e);
        return ERROR_GENERAL;
    } catch (IOException e) {
        logger.warn(e.getMessage(), e);
        // probably something with the Internet..
        return ERROR_NET;
    }
}

From source file:com.cloudant.mazha.HttpRequests.java

protected void setEntity(HttpEntityEnclosingRequestBase httpRequest, String json) {
    try {//  www. j  ava  2 s  .com
        StringEntity entity = new StringEntity(json, "UTF-8");
        entity.setContentType("application/json");
        httpRequest.setEntity(entity);
    } catch (UnsupportedEncodingException e) {
        throw new IllegalArgumentException(e);
    }
}