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.TracyAsyncHttpClientPublisher.java

@Override
public boolean publish(String tracySegment) {
    boolean published = true;
    HttpPost httpPost;//from w  w  w . j ava2s  .  c  om
    if (null != this.uri) {
        if (httpProxyConfig.isEnabled()) {
            HttpHost proxy = new HttpHost(httpProxyConfig.getHost(), httpProxyConfig.getPort(), "http");
            RequestConfig reqConfig = RequestConfig.custom().setProxy(proxy).setAuthenticationEnabled(true)
                    .setProxyPreferredAuthSchemes(Arrays.asList(AuthSchemes.BASIC)).build();
            httpPost = new HttpPost(uri);
            httpPost.setConfig(reqConfig);
        } else {
            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);
            Future<HttpResponse> future = httpClient.execute(httpPost, null);
            if (waitForResponse) {
                HttpResponse response = future.get();
                published = (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK);
                if (debug) {
                    System.out.println(extractPostResponse(response));
                }
            }
        } catch (Exception e) {
        }
    }
    return published;
}

From source file:org.cvasilak.jboss.mobile.admin.net.TalkToJBossServerTask.java

@Override
protected JsonElement doInBackground(ParametersMap... objects) {
    if (client == null) {
        return null;
    }/*from  w w  w  . j a v a2 s . c  om*/

    ParametersMap params = objects[0];

    // ask the server to pretty print
    params.add("json.pretty", Boolean.TRUE);

    try {
        String json = gjson.toJson(params);
        StringEntity entity = new StringEntity(json, "UTF-8");
        entity.setContentType("application/json");

        HttpPost httpRequest = new HttpPost(server.getHostPort() + "/management");
        httpRequest.setEntity(entity);

        Log.d(TAG, "--------> " + json);

        HttpResponse serverResponse = client.execute(httpRequest);

        JBossResponseHandler handler = new JBossResponseHandler();
        String response = handler.handleResponse(serverResponse);

        Log.d(TAG, "<-------- " + response);

        return parser.parse(response).getAsJsonObject();

    } catch (Exception e) {
        this.exception = e;
        cancel(true);
    }

    return null;
}

From source file:org.hydracache.server.httpd.handler.MethodBasedRequestDispatcher.java

private void handleException(HttpResponse response, Exception ex) {
    log.debug("Error occured while handling request: ", ex);
    response.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);
    try {//from  w w w  . ja  va2s  . c  o m
        StringEntity body = new StringEntity(
                StringUtils.isEmpty(ex.getMessage()) ? GENERIC_ERROR_MESSAGE : ex.getMessage());
        body.setContentType(PLAIN_TEXT_RESPONSE_CONTENT_TYPE);
        response.setEntity(body);
    } catch (UnsupportedEncodingException e) {
        log.error("Failed to generate response: ", e);
    }
}

From source file:org.opendaylight.infrautils.diagstatus.shell.HttpClient.java

public HttpResponse sendRequest(HttpRequest request) throws Exception {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    if (httpclient == null) {
        throw new ClientProtocolException("Couldn't create an HTTP client");
    }//from w w w  .j  av a 2 s  .  c  o m
    RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(request.getTimeout())
            .setConnectTimeout(request.getTimeout()).build();
    HttpRequestBase httprequest;
    String method = request.getMethod();
    if (method.equalsIgnoreCase("GET")) {
        httprequest = new HttpGet(request.getUri());
    } else if (method.equalsIgnoreCase("POST")) {
        httprequest = new HttpPost(request.getUri());
        if (request.getEntity() != null) {
            StringEntity sentEntity = new StringEntity(request.getEntity());
            sentEntity.setContentType(request.getContentType());
            ((HttpEntityEnclosingRequestBase) httprequest).setEntity(sentEntity);
        }
    } else if (method.equalsIgnoreCase("PUT")) {
        httprequest = new HttpPut(request.getUri());
        if (request.getEntity() != null) {
            StringEntity sentEntity = new StringEntity(request.getEntity());
            sentEntity.setContentType(request.getContentType());
            ((HttpEntityEnclosingRequestBase) httprequest).setEntity(sentEntity);
        }
    } else if (method.equalsIgnoreCase("DELETE")) {
        httprequest = new HttpDelete(request.getUri());
    } else {
        httpclient.close();
        throw new IllegalArgumentException(
                "This profile class only supports GET, POST, PUT, and DELETE methods");
    }
    httprequest.setConfig(requestConfig);
    // add request headers
    Iterator<String> headerIterator = request.getHeaders().keySet().iterator();
    while (headerIterator.hasNext()) {
        String header = headerIterator.next();
        Iterator<String> valueIterator = request.getHeaders().get(header).iterator();
        while (valueIterator.hasNext()) {
            httprequest.addHeader(header, valueIterator.next());
        }
    }
    CloseableHttpResponse response = httpclient.execute(httprequest);
    try {
        int httpResponseCode = response.getStatusLine().getStatusCode();
        HashMap<String, List<String>> headerMap = new HashMap<>();
        // copy response headers
        HeaderIterator it = response.headerIterator();
        while (it.hasNext()) {
            Header nextHeader = it.nextHeader();
            String name = nextHeader.getName();
            String value = nextHeader.getValue();
            if (headerMap.containsKey(name)) {
                headerMap.get(name).add(value);
            } else {
                List<String> list = new ArrayList<>();
                list.add(value);
                headerMap.put(name, list);
            }
        }
        if (httpResponseCode > 299) {
            return new HttpResponse(httpResponseCode, response.getStatusLine().getReasonPhrase(), headerMap);
        }
        Optional<HttpEntity> receivedEntity = Optional.ofNullable(response.getEntity());
        String httpBody = receivedEntity.isPresent() ? EntityUtils.toString(receivedEntity.get()) : null;
        return new HttpResponse(response.getStatusLine().getStatusCode(), httpBody, headerMap);
    } finally {
        response.close();
    }
}

From source file:org.droidparts.http.RESTClient.java

public String post(String uri, String contentEncoding, String data) throws HTTPException {
    L.d("POST on " + uri + ", data: " + data);
    // TODO useHttpURLConnection()
    HttpPost req = new HttpPost(uri);
    try {/* w w  w  .  j  a  va2s .c  om*/
        StringEntity entity = new StringEntity(data, UTF8);
        entity.setContentType(contentEncoding);
        req.setEntity(entity);
    } catch (UnsupportedEncodingException e) {
        L.e(e);
        throw new HTTPException(e);
    }
    DefaultHttpClientWrapper wrapper = getLegacy();
    HttpResponse resp = wrapper.getResponse(req);
    String respStr = DefaultHttpClientWrapper.getResponseBody(resp);
    DefaultHttpClientWrapper.consumeResponse(resp);
    return respStr;
}

From source file:it.sasabz.android.sasabus.classes.hafas.XMLAsyncRequest.java

@Override
protected String doInBackground(Void... params) {
    String ret = "";
    if (!haveNetworkConnection()) {
        return ret;
    }//from   ww  w.  j  a  v  a  2  s . c  o m
    try {
        HttpClient http = new DefaultHttpClient();
        HttpPost post = new HttpPost(SASAbus.getContext().getString(R.string.xml_server));
        StringEntity se = new StringEntity(request, HTTP.UTF_8);
        se.setContentType("text/xml");
        post.setEntity(se);

        HttpResponse response = http.execute(post);
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            ret = EntityUtils.toString(response.getEntity());
        }
    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return ret;
}

From source file:boosta.artem.services.TaskQuery.java

public int addTask() throws UnsupportedEncodingException, IOException, ParseException {

    int task_id = 0;

    DefaultHttpClient httpClient = new DefaultHttpClient();
    HttpPost httpPost = new HttpPost("http://62.210.82.210:9091/API");
    StringEntity requestEntity = new StringEntity(this.task.toJSON(), "UTF-8");
    requestEntity.setContentType("application/json");
    System.out.println(getStringFromInputStream(requestEntity.getContent()) + "\n");
    httpPost.setEntity(requestEntity);/*  w  ww.j  a v a 2s .  c om*/
    HttpResponse response = httpClient.execute(httpPost);

    InputStream in = response.getEntity().getContent();

    String resp = getStringFromInputStream(in);
    //resp.getBytes("UTF-8");

    //resp = resp.getBytes(resp).toString();

    System.out.println(resp);

    JSONParser parser = new JSONParser();

    JSONObject json = (JSONObject) parser.parse(resp);
    //json.toJSONString();
    task_id = Integer.parseInt(json.get("data").toString());

    System.out.println(task_id);

    return task_id;
}

From source file:com.squid.kraken.v4.auth.ChangePasswordServlet.java

/**
 * Perform the action via API calls./*  w w  w  .j av a2 s  .c o m*/
 *
 * @param request
 * @param response
 * @throws ServletException
 * @throws IOException
 */
private void proceed(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException, URISyntaxException {
    try {
        User user = getUser(request);
        user.setPassword(request.getParameter("password"));

        // create a POST method to execute the change password request
        URIBuilder builder = new URIBuilder(privateServerURL + "/rs/users/");
        String token = request.getParameter("access_token");
        builder.addParameter("access_token", token);

        // execute the request
        HttpPost req = new HttpPost(builder.build());
        Gson gson = new Gson();
        String json = gson.toJson(user);
        StringEntity stringEntity = new StringEntity(json);
        stringEntity.setContentType("application/json");
        req.setEntity(stringEntity);
        user = RequestHelper.processRequest(User.class, request, req);
        request.setAttribute("message", "Password updated");
        request.setAttribute("user", user);
        RequestDispatcher rd = getServletContext().getRequestDispatcher("/password.jsp");
        rd.forward(request, response);
    } catch (ServerUnavailableException e1) {
        logger.error(e1.getLocalizedMessage());
        request.setAttribute(KRAKEN_UNAVAILABLE, Boolean.TRUE);
        show(request, response);
    } catch (ServiceException e1) {
        WebServicesException wsException = e1.getWsException();
        String error;
        if (wsException == null) {
            error = AN_ERROR_OCCURRED;
        } else {
            error = wsException.getError();
        }
        request.setAttribute(ERROR, error);
        show(request, response);
    } catch (SSORedirectException error) {
        response.sendRedirect(error.getRedirectURL());
    }
}

From source file:org.doubango.ngn.services.impl.NgnHttpClientService.java

@Override
public String post(String uri, String contentUTF8, String contentType) {
    String result = null;//from w w  w.  j  a  v a 2 s  .  c om
    try {
        HttpPost postRequest = new HttpPost(uri);
        final StringEntity entity = new StringEntity(contentUTF8, "UTF-8");
        if (contentType != null) {
            entity.setContentType(contentType);
        }
        postRequest.setEntity(entity);
        final HttpResponse resp = mClient.execute(postRequest);
        if (resp != null) {
            return getResponseAsString(resp);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return result;
}

From source file:org.droidparts.http.RESTClient.java

public String put(String uri, String contentEncoding, String data) throws HTTPException {
    L.d("PUT on " + uri + ", data: " + data);
    // TODO useHttpURLConnection()
    HttpPut req = new HttpPut(uri);
    try {/* w w w.  j  ava2 s . c om*/
        StringEntity entity = new StringEntity(data, UTF8);
        entity.setContentType(contentEncoding);
        req.setEntity(entity);
    } catch (UnsupportedEncodingException e) {
        throw new HTTPException(e);
    }
    DefaultHttpClientWrapper wrapper = getLegacy();
    HttpResponse resp = wrapper.getResponse(req);
    Header loc = resp.getLastHeader("Location");
    DefaultHttpClientWrapper.consumeResponse(resp);
    if (loc != null) {
        String[] parts = loc.getValue().split("/");
        String location = parts[parts.length - 1];
        L.d("location: " + location);
        return location;
    } else {
        return null;
    }
}