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

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

Introduction

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

Prototype

public StringEntity(String str) throws UnsupportedEncodingException 

Source Link

Usage

From source file:de.lgblaumeiser.ptm.cli.rest.RestUtils.java

/**
 * Post a call to the rest api. Expects that a numerical id is returned as
 * part of the creation call./*from   w w  w.j a  v  a2 s.  c o m*/
 * 
 * @param apiName
 *            Name of the api
 * @param bodyData
 *            Body of the post data, this is a flat map that is converted
 *            into a flat json
 * @return The Id of the created or manipulated object
 */
public Long post(String apiName, Map<String, String> bodyData) {
    try {
        final HttpPost request = new HttpPost(baseUrl + apiName);
        StringEntity bodyJson = new StringEntity(jsonMapper.writeValueAsString(bodyData));
        bodyJson.setContentType("application/json");
        bodyJson.setContentEncoding("UTF-8");
        request.setEntity(bodyJson);
        HttpResponse response = clientConnector.execute(request);
        checkState(
                response.getStatusLine().getStatusCode() == 201
                        || response.getStatusLine().getStatusCode() == 200,
                "Cannot access server properly, Status " + response.getStatusLine() + ", URI: " + apiName);
        String uri = apiName;
        if (response.getStatusLine().getStatusCode() == 201) {
            uri = response.getHeaders("Location")[0].getValue();
        }
        return Long.parseLong(uri.substring(uri.lastIndexOf("/") + 1));
    } catch (IOException e) {
        throw new IllegalStateException(e);
    }

}

From source file:org.fashiontec.bodyapps.sync.Sync.java

/**
 * Method which makes all the post calls
 *
 * @param url/*from  ww  w.ja v a2  s . com*/
 * @param json
 * @return
 */
public HttpResponse post(String url, String json, int conTimeOut, int socTimeOut) {
    HttpResponse response = null;
    try {

        HttpParams httpParameters = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(httpParameters, conTimeOut);
        HttpConnectionParams.setSoTimeout(httpParameters, socTimeOut);
        HttpClient httpclient = new DefaultHttpClient(httpParameters);
        HttpPost httpPost = new HttpPost(url);
        StringEntity se = new StringEntity(json);
        httpPost.setEntity(se);
        httpPost.setHeader("Accept", "application/json");
        httpPost.setHeader("Content-type", "application/json");
        response = httpclient.execute(httpPost);
    } catch (Exception e) {
        Log.e(TAG, e.getMessage());
    }

    return response;
}

From source file:org.fcrepo.integration.generator.AbstractResourceIT.java

protected static HttpPost postDSMethod(final String pid, final String ds, final String content)
        throws UnsupportedEncodingException {
    final HttpPost post = new HttpPost(
            serverAddress + pid + "/" + ds + "?mixin=" + FedoraJcrTypes.FEDORA_DATASTREAM);
    post.setEntity(new StringEntity(content));
    return post;/*from   w w  w.  j  a  v a  2  s  .  co  m*/
}

From source file:at.ac.tuwien.dsg.cloudlyra.utils.QualityEvaluatorREST.java

public void callQualityEvaluator(String xmlString) {

    try {/*from w w  w  .ja va 2 s  . com*/
        String url = "http://" + ip + ":" + port + "/RESTWSTEST/webresources/daf";

        //  String url = "http://" + ip + ":" + port + "/QualityEvaluator/webresources/QualityEvaluator";
        //HttpGet method = new HttpGet(url);
        StringEntity inputKeyspace = new StringEntity(xmlString);

        HttpPut request = new HttpPut(url);
        request.addHeader("content-type", "application/xml; charset=utf-8");
        request.addHeader("Accept", "application/xml, multipart/related");
        request.setEntity(inputKeyspace);

        HttpResponse methodResponse = this.getHttpClient().execute(request);

        int statusCode = methodResponse.getStatusLine().getStatusCode();

        System.out.println("Status Code: " + statusCode);

        BufferedReader rd = new BufferedReader(new InputStreamReader(methodResponse.getEntity().getContent()));

        StringBuilder result = new StringBuilder();
        String line;
        while ((line = rd.readLine()) != null) {
            result.append(line);
        }

        // System.out.println("Response String: " + result.toString());
    } catch (Exception ex) {

    }

}

From source file:org.opentravel.otm.forum2016.am.CreateAPIDocumentOperation.java

/**
 * @see org.opentravel.otm.forum2016.am.RESTClientOperation#execute()
 *///w  ww  .jav a  2 s.c o m
@Override
public APIDocument execute() throws IOException {
    HttpPost request = new HttpPost(
            APIPublisherConfig.getWSO2PublisherApiBaseUrl() + "/" + apiId + "/documents");

    request.setHeader("Content-Type", "application/json");
    request.setEntity(new StringEntity(new Gson().toJson(document.toJson())));
    return execute(request);
}

From source file:thread.MyThread.java

public void run() {
    try {//from   w ww  .  j a v a2 s . c om
        gate.await();
        System.out.println("Run : " + obj.toString());
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);
        httpPost.setHeader("Accept-Content Type", acceptType);
        httpPost.setHeader("Content-type", contentType);
        httpPost.setEntity(new StringEntity(obj.toString()));
        long startTime = System.currentTimeMillis();
        CloseableHttpResponse httpResponse = httpClient.execute(httpPost);
        long endTime = System.currentTimeMillis();
        time = endTime - startTime;
        if (httpResponse.getStatusLine().getStatusCode() == 200) {
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(httpResponse.getEntity().getContent()));
            String inputLine;
            StringBuffer response = new StringBuffer();
            while ((inputLine = reader.readLine()) != null) {
                response.append(inputLine);
            }
            reader.close();
            JsonObject jresp = new JsonObject();
            Gson gson = new Gson();
            jresp = gson.fromJson(response.toString(), JsonObject.class);
            //                JsonElement je = jresp.get("code");

            code = jresp.toString();
            //                System.out.println("Thread - data resp: " + jresp.toString());
        } else {
            System.out.println("API Fail status code = " + httpResponse.getStatusLine().getStatusCode());
            //            return new DataResponseWithdrawFunds();/
            code = "-1";
        }
    } catch (UnsupportedEncodingException ex) {
        Logger.getLogger(MyThread.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(MyThread.class.getName()).log(Level.SEVERE, null, ex);
    } catch (InterruptedException ex) {
        Logger.getLogger(MyThread.class.getName()).log(Level.SEVERE, null, ex);
    } catch (BrokenBarrierException ex) {
        Logger.getLogger(MyThread.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:com.fpmislata.banco.business.service.impl.PeticionRetirarDineroServiceImpl.java

@Override
public void sendPeticionBancaria(CredencialesBancarias credencialesBancarias, String cccOrigen, String concepto,
        BigDecimal importe, String codigoEntidadBancaria) throws BusinessException {
    CloseableHttpClient httpClient = HttpClients.createDefault();
    try {//from  ww w .  j  ava  2  s . c  o  m
        Extraccion extraccion = new Extraccion();

        extraccion.setCodigoCuentaCliente(cccOrigen);
        extraccion.setCodigoEntidadBancaria(codigoEntidadBancaria);
        extraccion.setConcepto(concepto);
        extraccion.setImporte(importe);
        extraccion.setPin(credencialesBancarias.getPin());

        HttpPost httpPost = new HttpPost(credencialesBancarias.getUrl() + "/retirar");
        StringEntity stringEntity = new StringEntity(jsonTransformer.toJson(extraccion));
        httpPost.setEntity(stringEntity);
        httpPost.setHeader("Content-type", "application/json");
        httpClient.execute(httpPost);
    } catch (IOException ex) {
        Logger.getLogger(BancoCentralServiceImpl.class.getName()).log(Level.SEVERE, null, ex);
        throw new BusinessException("Error por cuestiones ajenas", "BancoCentral");
    } finally {
        try {
            httpClient.close();
        } catch (IOException ex) {
            Logger.getLogger(BancoCentralServiceImpl.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

From source file:main.java.com.skillselector.client.root.Neo4JRequest.java

public Map<String, HashMap<String, String>> getContent(String postAddress, String Payload) {
    Map<String, HashMap<String, String>> content = new HashMap<String, HashMap<String, String>>();
    HttpClient client = new DefaultHttpClient();

    HttpPost httppost = new HttpPost(postAddress);
    httppost.setHeader("Content-Type", "text/x-gwt-rpc; charset=UTF-8");
    StringEntity se;//from www .  j  a  va2  s  .c om
    try {
        se = new StringEntity(Payload);
        httppost.setEntity(se);
        HttpResponse response = client.execute(httppost);
        String json = EntityUtils.toString(response.getEntity());
        JSONObject temp1 = new JSONObject(json);
        JSONArray array = (JSONArray) temp1.get("data");
        //  System.out.println(json);
        for (int i = 0; i < array.length(); i++) {
            JSONArray subarray = (JSONArray) array.get(i);
            if (content.containsKey(subarray.get(0))) {
                HashMap<String, String> submap = content.get(subarray.get(0));
                submap.put(subarray.getString(1), subarray.getString(2));

            } else {
                HashMap<String, String> submap = new HashMap<String, String>();
                submap.put(subarray.getString(1), subarray.getString(2));
                content.put((String) subarray.get(0), submap);
            }
        }
    } catch (UnsupportedEncodingException ex) {
        Logger.getLogger(Neo4JRequest.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException e) {
        Logger.getLogger(Neo4JRequest.class.getName()).log(Level.SEVERE, null, e);
    }

    return content;
}

From source file:uk.ac.bbsrc.tgac.miso.integration.util.IntegrationUtils.java

public static String makePostRequest(String host, int port, String query) throws IntegrationException {
    if (query == null || query.isEmpty()) {
        throw new IntegrationException("Query must be populated when calling makePostRequest.");
    }//from  w  w  w  .  j a va2  s  .c o m

    String rtn = null;
    HttpClient httpclient = HttpClientBuilder.create().build();
    String url = "http://" + host + ":" + port + "/miso/";

    try {
        HttpPost httpPost = new HttpPost(url);
        // Request parameters and other properties.
        httpPost.setHeader("content-type", "application/x-www-form-urlencoded");
        System.out.println(query);
        httpPost.setEntity(new StringEntity(query));

        // Execute and get the response.
        HttpResponse response = httpclient.execute(httpPost);
        rtn = EntityUtils.toString(response.getEntity());
        if (rtn.charAt(0) == '"' && rtn.charAt(rtn.length() - 1) == '"') {
            System.out.println("Removing quotes");
            rtn = rtn.substring(1, rtn.length() - 1);
        }
    } catch (IOException ex) {
        ex.printStackTrace();
        throw new IntegrationException("Cannot connect to " + url + " Cause: " + ex.getMessage());

    }
    return rtn;

}

From source file:es.upm.fiware.rss.settlement.SettlementNotifier.java

public void notifyProvider() {
    // Makes a POST request to the specified callback URL
    HttpClient client = new DefaultHttpClient();
    HttpPost post = new HttpPost(this.pool.getCallbackUrl());
    post.setHeader("Content-type", MediaType.APPLICATION_JSON);

    Map<String, String> data = new HashMap<>();
    data.put("status", pool.getState().toString());

    try {/*  www  .ja  v a  2 s  .  co  m*/
        HttpEntity entity = new StringEntity(new JSONObject(data).toString());
        post.setEntity(entity);

        // A failure in the notification must not block the system
        client.execute(post);
    } catch (UnsupportedEncodingException ex) {
        Logger.getLogger(SettlementNotifier.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(SettlementNotifier.class.getName()).log(Level.SEVERE, null, ex);
    }
}