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:org.fcrepo.serialization.bagit.BagItSerializerIT.java

@Test
public void tryOneObject() throws ClientProtocolException, IOException {
    client.execute(postObjMethod("BagIt1"));
    client.execute(postDSMethod("BagIt1", "testDS", "stuff"));
    final HttpGet getObjMethod = new HttpGet(serverAddress + "objects/BagIt1/fcr:export?format=bagit");
    HttpResponse response = client.execute(getObjMethod);
    assertEquals(200, response.getStatusLine().getStatusCode());
    final String content = EntityUtils.toString(response.getEntity());
    logger.debug("Found exported object: " + content);
    client.execute(new HttpDelete(serverAddress + "objects/BagIt1"));
    logger.debug("Deleted test object.");
    final HttpPost importMethod = new HttpPost(serverAddress + "objects/fcr:import?format=bagit");
    importMethod.setEntity(new StringEntity(content));
    assertEquals("Couldn't import!", 201, getStatus(importMethod));
    final HttpGet httpGet = new HttpGet(serverAddress + "objects/BagIt1");
    httpGet.setHeader("Accepts", "application/n3");
    response = client.execute(httpGet);//from  w  w  w.j a  v  a 2 s. c o  m
    assertEquals("Couldn't find reimported object!", 200, response.getStatusLine().getStatusCode());
    response = client.execute(new HttpGet(serverAddress + "objects/BagIt1/testDS"));
    assertEquals("Couldn't find reimported datastream!", 200, response.getStatusLine().getStatusCode());
    logger.debug("Successfully reimported!");
}

From source file:com.obomprogramador.dropbackend.TestLogin.java

private int sendRequest(String sentity) {
    int resultCode = -1;
    try {/*from w  ww. j a va 2  s .  c  o m*/
        HttpHost target = new HttpHost("localhost", 8080, "http");
        HttpPost postRequest = new HttpPost("/api/login");

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

        logger.debug("### executing request to " + target);

        HttpResponse httpResponse = httpclient.execute(target, postRequest);
        HttpEntity entity = httpResponse.getEntity();

        logger.debug("### ----------------------------------------");
        logger.debug("### " + httpResponse.getStatusLine());
        Header[] headers = httpResponse.getAllHeaders();
        for (int i = 0; i < headers.length; i++) {
            logger.debug("### " + headers[i]);
        }
        logger.debug("### ----------------------------------------");

        if (entity != null) {
            logger.debug("### " + EntityUtils.toString(entity));
            resultCode = httpResponse.getStatusLine().getStatusCode();
        }

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

From source file:com.sandopolus.yeildify.service1.resources.RamdomResourceImpl.java

@POST
public RandomMessage generateRandomValue(Message msg) {
    try {/*  w ww.j a v a2 s .c om*/
        HttpPost req = new HttpPost("http://service2:8080/reverse");
        req.addHeader("accept", "application/json");
        req.addHeader("content-type", "application/json");
        req.setEntity(new StringEntity(JSON_MAPPER.writeValueAsString(msg)));

        HttpResponse resp = HTTP_CLIENT.execute(req);
        if (resp.getStatusLine().getStatusCode() != 200) {
            throw new InternalServerErrorException(
                    "Service2 returned status code " + resp.getStatusLine().getStatusCode());
        }
        Message reversedMessage = JSON_MAPPER.readValue(resp.getEntity().getContent(), Message.class);

        RandomMessage result = new RandomMessage();
        result.setMessage(reversedMessage.getMessage());
        result.setRand(RAND.nextDouble());
        return result;
    } catch (IOException ex) {
        throw new InternalServerErrorException("Error with comms to service2");
    }
}

From source file:org.paolomoz.zehnkampf.utils.TestGenHTTPResponse.java

public void testWriteResponse() throws IOException {
    HttpEntity entity = new StringEntity(entityString);

    HttpResponse response = new BasicHttpResponse(new ProtocolVersion("HTTP", 1, 1), HttpStatus.SC_OK, "OK");
    response.setHeader("Content-length", new Integer(entityString.length()).toString());
    response.setEntity(entity);//  w  w  w.j ava  2s.  c  o m

    assertEquals(1, response.getAllHeaders().length);
    assertEquals("HTTP/1.1 200 OK", response.getStatusLine().toString());

    OutputStream out = new ByteArrayOutputStream();
    genHTTPResp.writeResponse(response, out);

    assertEquals("HTTP/1.1 200 OK\r\n" + "Content-length: 4\r\n" + "\r\n" + "test", out.toString());
}

From source file:ly.apps.androdi.rest.tests.JsonBodyConverterTest.java

public void testToRequestBody() throws IOException {
    String requestBody = FileUtils.convertStreamToString(
            converter.toRequestBody(SampleBean.testInstance(), HeaderUtils.CONTENT_TYPE_JSON).getContent());
    assertEquals(SampleBean.testInstance(), converter.fromResponseBody(SampleBean.class,
            HeaderUtils.CONTENT_TYPE_JSON, new StringEntity(requestBody), new TestCallback<SampleBean>()));
}

From source file:fr.xebia.workshop.android.core.utils.ServerUtils.java

private static HttpPost buildRegistationIdRequest(String registrationId, String deviceId, Long userId)
        throws JSONException, UnsupportedEncodingException {
    HttpPost putRequest = new HttpPost(GCM_REGISTRATION_URL);
    putRequest.setHeader(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
    JSONObject regObject = new JSONObject();
    regObject.put("deviceId", deviceId);
    regObject.put("registrationId", registrationId);
    JSONObject userObject = new JSONObject();
    userObject.put("id", userId);
    regObject.put("user", userObject);
    putRequest.setEntity(new StringEntity(regObject.toString()));
    return putRequest;
}

From source file:com.yanzhenjie.andserver.sample.response.RequestFileHandler.java

@Override
public void handle(HttpRequest request, HttpResponse response, HttpContext context)
        throws HttpException, IOException {
    // You can according to the client param can also be downloaded.

    File file = new File(mFilePath);
    if (file.exists()) {
        response.setStatusCode(200);/*from w  w  w  .  j a v  a 2 s .c  om*/

        long contentLength = file.length();
        response.setHeader("ContentLength", Long.toString(contentLength));
        response.setEntity(new FileEntity(file, HttpRequestParser.getMimeType(file.getName())));
    } else {
        response.setStatusCode(404);
        response.setEntity(new StringEntity(""));
    }
}

From source file:net.acesinc.data.json.generator.log.HttpPostLogger.java

private void logEvent(String event) {
    try {//from   w ww .  ja va 2s.c  o  m
        HttpPost request = new HttpPost(url);
        StringEntity input = new StringEntity(event);
        input.setContentType("application/json");
        request.setEntity(input);

        //            log.debug("executing request " + request);
        CloseableHttpResponse response = null;
        try {
            response = httpClient.execute(request);
        } catch (IOException ex) {
            log.error("Error POSTing Event", ex);
        }
        if (response != null) {
            try {
                //                    log.debug("----------------------------------------");
                //                    log.debug(response.getStatusLine().toString());
                HttpEntity resEntity = response.getEntity();
                if (resEntity != null) {
                    //                        log.debug("Response content length: " + resEntity.getContentLength());
                }
                EntityUtils.consume(resEntity);
            } catch (IOException ioe) {
                //oh well
            } finally {
                try {
                    response.close();
                } catch (IOException ex) {
                }
            }
        }
    } catch (Exception e) {

    }
}

From source file:es.uned.dia.jcsombria.softwarelinks.transport.HttpTransport.java

public Object send(String request) throws Exception {
    Object response = null;/*ww  w .  ja  v  a2 s  . c o  m*/
    CloseableHttpClient httpclient = HttpClients.createDefault();
    try {
        HttpPost httppost = new HttpPost(serverURL.toString());
        httppost.setEntity(new StringEntity(request));
        // Create a custom response handler
        ResponseHandler<String> responseHandler = new ResponseHandler<String>() {
            public String handleResponse(final HttpResponse response)
                    throws ClientProtocolException, IOException {
                int status = response.getStatusLine().getStatusCode();
                if (status >= 200 && status < 300) {
                    HttpEntity entity = response.getEntity();
                    return entity != null ? EntityUtils.toString(entity) : null;
                } else {
                    throw new ClientProtocolException("Unexpected response status: " + status);
                }
            }
        };
        String responseBody = httpclient.execute(httppost, responseHandler);
        response = responseBody;
    } finally {
        httpclient.close();
    }
    return response;
}

From source file:diuf.unifr.ch.first.xwot.notifications.OpenNotificationBuilder.java

/**
 * Encode into xml the Open JAXB class// w  w w  .  j av a  2s . c o m
 * 
 * @see Open
 * @param client
 * @return instance of a StringEntity containg xml informations
 */
@Override
public StringEntity jaxbToStringEntity(Client client) {
    StringEntity body = null;
    if (open == null || !open.equalsToOpen(oldOpen)) {
        setOpen();
    }
    try {
        body = new StringEntity(jaxbToXml(Open.class, open));
        body.setContentType("application/xml");
    } catch (UnsupportedEncodingException ex) {
        logger.error("Unable to encode StringEntity", ex);
    }
    return body;
}