Example usage for org.apache.http.client.methods HttpPost setEntity

List of usage examples for org.apache.http.client.methods HttpPost setEntity

Introduction

In this page you can find the example usage for org.apache.http.client.methods HttpPost setEntity.

Prototype

public void setEntity(final HttpEntity entity) 

Source Link

Usage

From source file:org.sharetask.data.IntegrationTest.java

@BeforeClass
public static void login() throws Exception {
    final DefaultHttpClient client = new DefaultHttpClient();
    final HttpPost httpPost = new HttpPost(BASE_URL + "/user/login");
    httpPost.addHeader(new BasicHeader("Content-Type", "application/json"));
    final StringEntity httpEntity = new StringEntity(
            "{\"username\":\"dev1@shareta.sk\"," + "\"password\":\"password\"}");
    System.out.println(EntityUtils.toString(httpEntity));
    httpPost.setEntity(httpEntity);

    //when//from   w  ww .  j a  v a  2  s  . co  m
    final HttpResponse response = client.execute(httpPost);

    //then
    Assert.assertEquals(HttpStatus.OK.value(), response.getStatusLine().getStatusCode());
    client.getCookieStore().getCookies();
    for (final Cookie cookie : client.getCookieStore().getCookies()) {
        if (cookie.getName().equals("JSESSIONID")) {
            DOMAIN = cookie.getDomain();
            SESSIONID = cookie.getValue();
        }
    }
}

From source file:com.bearstech.android.myownsync.client.NetworkUtilities.java

/**
 * Fetches status messages for the user's friends from the server
 * /*from w w  w . java 2s.  co  m*/
 * @param account The account being synced.
 * @param authtoken The authtoken stored in the AccountManager for the
 *        account
 * @return list The list of status messages received from the server.
 */
public static List<User.Status> fetchFriendStatuses(Account account, String authtoken)
        throws JSONException, ParseException, IOException, AuthenticationException {
    Log.d(TAG, "fetchFriendStatuses");
    final ArrayList<User.Status> statusList = new ArrayList<User.Status>();
    final ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new BasicNameValuePair(PARAM_USERNAME, account.name));
    params.add(new BasicNameValuePair(PARAM_PASSWORD, authtoken));

    HttpEntity entity = null;
    entity = new UrlEncodedFormEntity(params);
    final HttpPost post = new HttpPost(base_url + FETCH_STATUS_URI);
    post.addHeader(entity.getContentType());
    post.setEntity(entity);
    maybeCreateHttpClient();

    final HttpResponse resp = mHttpClient.execute(post);
    final String response = EntityUtils.toString(resp.getEntity());

    if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
        // Succesfully connected to the samplesyncadapter server and
        // authenticated.
        // Extract friends data in json format.
        final JSONArray statuses = new JSONArray(response);
        for (int i = 0; i < statuses.length(); i++) {
            statusList.add(User.Status.valueOf(statuses.getJSONObject(i)));
        }
    } else {
        if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_UNAUTHORIZED) {
            Log.e(TAG, "Authentication exception in fetching friend status list");
            throw new AuthenticationException();
        } else {
            Log.e(TAG, "Server error in fetching friend status list");
            throw new IOException();
        }
    }
    return statusList;
}

From source file:cz.muni.fi.webmias.TeXConverter.java

/**
 * Converts TeX formula to MathML using LaTeXML through a web service.
 *
 * @param query String containing one or more keywords and TeX formulae
 * (formulae enclosed in $ or $$)./* w w w.j  a  va2 s  . co m*/
 * @return String containing formulae converted to MathML that replaced
 * original TeX forms. Non math tokens are connected at the end.
 */
public static String convertTexLatexML(String query) {
    query = query.replaceAll("\\$\\$", "\\$");
    if (query.matches(".*\\$.+\\$.*")) {
        try {
            HttpClient httpclient = HttpClients.createDefault();
            HttpPost httppost = new HttpPost(LATEX_TO_XHTML_CONVERSION_WS_URL);

            // Request parameters and other properties.
            List<NameValuePair> params = new ArrayList<>(1);
            params.add(new BasicNameValuePair("code", query));
            httppost.setEntity(new UrlEncodedFormEntity(params, StandardCharsets.UTF_8));

            // Execute and get the response.
            HttpResponse response = httpclient.execute(httppost);
            if (response.getStatusLine().getStatusCode() == 200) {
                HttpEntity resEntity = response.getEntity();
                if (resEntity != null) {
                    try (InputStream responseContents = resEntity.getContent()) {
                        DocumentBuilder dBuilder = MIaSUtils.prepareDocumentBuilder();
                        org.w3c.dom.Document doc = dBuilder.parse(responseContents);
                        NodeList ps = doc.getElementsByTagName("p");
                        String convertedMath = "";
                        for (int k = 0; k < ps.getLength(); k++) {
                            Node p = ps.item(k);
                            NodeList pContents = p.getChildNodes();
                            for (int j = 0; j < pContents.getLength(); j++) {
                                Node pContent = pContents.item(j);
                                if (pContent instanceof Text) {
                                    convertedMath += pContent.getNodeValue() + "\n";
                                } else {
                                    TransformerFactory transFactory = TransformerFactory.newInstance();
                                    Transformer transformer = transFactory.newTransformer();
                                    StringWriter buffer = new StringWriter();
                                    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
                                    transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
                                    transformer.transform(new DOMSource(pContent), new StreamResult(buffer));
                                    convertedMath += buffer.toString() + "\n";
                                }
                            }
                        }
                        return convertedMath;
                    }
                }
            }

        } catch (TransformerException | SAXException | ParserConfigurationException | IOException ex) {
            Logger.getLogger(ProcessServlet.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    return query;
}

From source file:com.splunk.shuttl.archiver.archive.ArchiveRestHandler.java

private static HttpUriRequest createBucketArchiveRequest(Bucket bucket) throws UnsupportedEncodingException {
    // CONFIG configure the host and port with a general solution.
    String requestString = "http://localhost:9090/" + ShuttlConstants.ENDPOINT_CONTEXT
            + ShuttlConstants.ENDPOINT_ARCHIVER + ShuttlConstants.ENDPOINT_BUCKET_ARCHIVER;

    HttpPost request = new HttpPost(requestString);

    ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new BasicNameValuePair("path", bucket.getDirectory().getAbsolutePath()));
    params.add(new BasicNameValuePair("index", bucket.getIndex()));

    request.setEntity(new UrlEncodedFormEntity(params));
    return request;
}

From source file:info.androidhive.volleyjson.util.SslHttpStack.java

/**
 * Creates the appropriate subclass of HttpUriRequest for passed in request.
 *///from   w  ww . j  a  v  a  2  s  . c  o  m
@SuppressWarnings("deprecation")
/* protected */ static HttpUriRequest createHttpRequest(Request<?> request,
        Map<String, String> additionalHeaders) throws AuthFailureError {
    switch (request.getMethod()) {
    case Method.DEPRECATED_GET_OR_POST: {
        // This is the deprecated way that needs to be handled for backwards compatibility.
        // If the request's post body is null, then the assumption is that the request is
        // GET.  Otherwise, it is assumed that the request is a POST.
        byte[] postBody = request.getPostBody();
        if (postBody != null) {
            HttpPost postRequest = new HttpPost(request.getUrl());
            postRequest.addHeader(HEADER_CONTENT_TYPE, request.getPostBodyContentType());
            HttpEntity entity;
            entity = new ByteArrayEntity(postBody);
            postRequest.setEntity(entity);
            return postRequest;
        } else {
            return new HttpGet(request.getUrl());
        }
    }
    case Method.GET:
        return new HttpGet(request.getUrl());
    case Method.DELETE:
        return new HttpDelete(request.getUrl());
    case Method.POST: {
        HttpPost postRequest = new HttpPost(request.getUrl());
        postRequest.addHeader(HEADER_CONTENT_TYPE, request.getBodyContentType());
        //setMultiPartBody(postRequest,request);
        setEntityIfNonEmptyBody(postRequest, request);
        return postRequest;
    }
    case Method.PUT: {
        HttpPut putRequest = new HttpPut(request.getUrl());
        putRequest.addHeader(HEADER_CONTENT_TYPE, request.getBodyContentType());
        //setMultiPartBody(putRequest,request);
        setEntityIfNonEmptyBody(putRequest, request);
        return putRequest;
    }
    // Added in source code of Volley libray.
    case Method.PATCH: {
        HttpPatch patchRequest = new HttpPatch(request.getUrl());
        patchRequest.addHeader(HEADER_CONTENT_TYPE, request.getBodyContentType());
        setEntityIfNonEmptyBody(patchRequest, request);
        return patchRequest;
    }
    default:
        throw new IllegalStateException("Unknown request method.");
    }
}

From source file:com.github.robozonky.integrations.zonkoid.ZonkoidConfirmationProvider.java

static HttpPost getRequest(final RequestId requestId, final int loanId, final int amount, final String protocol,
        final String rootUrl) throws UnsupportedEncodingException {
    final String auth = getAuthenticationString(requestId, loanId);
    final HttpPost httpPost = new HttpPost(protocol + "://" + rootUrl + PATH);
    httpPost.addHeader("Accept", "text/plain");
    httpPost.addHeader("Authorization", auth);
    httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded");
    httpPost.addHeader("User-Agent", Defaults.ROBOZONKY_USER_AGENT);
    httpPost.setEntity(getFormData(requestId, loanId, amount));
    return httpPost;
}

From source file:com.dmsl.anyplace.utils.NetworkUtils.java

private static HttpEntity downloadHttpClientJsonPostHelp(String url, String json, int timeout)
        throws URISyntaxException, ClientProtocolException, IOException {

    HttpParams httpParameters = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(httpParameters, timeout);
    HttpConnectionParams.setSoTimeout(httpParameters, timeout);

    HttpClient client = new DefaultHttpClient(httpParameters);
    HttpPost request = new HttpPost(encodeURL(url));
    StringEntity se = new StringEntity(json);
    request.setEntity(se);
    request.setHeader("Accept", "application/json");
    request.setHeader("Content-type", "application/json");

    HttpResponse response = client.execute(request);

    int status = response.getStatusLine().getStatusCode();
    if (status != 200 && status != 400) {
        throw new RuntimeException("Server Error: " + response.getStatusLine().getReasonPhrase());
    }//  w  w  w .j  av a 2s .c o  m

    HttpEntity entity = response.getEntity();
    if (entity == null)
        throw new RuntimeException("Server Error: " + response.getStatusLine().getReasonPhrase());

    return entity;
}

From source file:core.VirusTotalAPIHelper.java

public static CloseableHttpResponse scanFile(File fileToScan) {
    if (apiKey == null || apiKey.isEmpty()) {
        return null;
    }//from   w w  w. j  a  v a  2  s  .  c o  m
    try {
        CloseableHttpClient client = HttpClients.createDefault();
        HttpPost httpsScanFilePost = new HttpPost(httpsPost + "file/scan");
        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        builder.addTextBody("apikey", apiKey);
        builder.addBinaryBody("file", fileToScan, ContentType.APPLICATION_OCTET_STREAM, fileToScan.getName());
        HttpEntity multipart = builder.build();
        httpsScanFilePost.setEntity(multipart);

        CloseableHttpResponse response = client.execute(httpsScanFilePost);
        return response;
    } catch (IOException ex) {
        Exceptions.printStackTrace(ex);
    }
    return null;
}

From source file:org.sakaiproject.contentreview.urkund.util.UrkundAPIUtil.java

public static String postDocument(String baseUrl, String receiverAddress, String externalId,
        UrkundSubmission submission, String urkundUsername, String urkundPassword, int timeout) {
    String ret = null;//from w  w  w .  j av  a 2  s. c  om

    RequestConfig.Builder requestBuilder = RequestConfig.custom();
    requestBuilder = requestBuilder.setConnectTimeout(timeout);
    requestBuilder = requestBuilder.setConnectionRequestTimeout(timeout);

    HttpClientBuilder builder = HttpClientBuilder.create();
    builder.setDefaultRequestConfig(requestBuilder.build());
    try (CloseableHttpClient httpClient = builder.build()) {

        HttpPost httppost = new HttpPost(baseUrl + "submissions/" + receiverAddress + "/" + externalId);
        //------------------------------------------------------------
        EntityBuilder eBuilder = EntityBuilder.create();
        eBuilder.setBinary(submission.getContent());

        httppost.setEntity(eBuilder.build());
        //------------------------------------------------------------
        if (StringUtils.isNotBlank(urkundUsername) && StringUtils.isNotBlank(urkundPassword)) {
            addAuthorization(httppost, urkundUsername, urkundPassword);
        }
        //------------------------------------------------------------
        httppost.addHeader("Accept", "application/json");
        httppost.addHeader("Content-Type", submission.getMimeType());
        httppost.addHeader("Accept-Language", submission.getLanguage());
        httppost.addHeader("x-urkund-filename", submission.getFilenameEncoded());
        httppost.addHeader("x-urkund-submitter", submission.getSubmitterEmail());
        httppost.addHeader("x-urkund-anonymous", Boolean.toString(submission.isAnon()));
        httppost.addHeader("x-urkund-subject", submission.getSubject());
        httppost.addHeader("x-urkund-message", submission.getMessage());
        //------------------------------------------------------------

        HttpResponse response = httpClient.execute(httppost);
        HttpEntity resEntity = response.getEntity();

        if (resEntity != null) {
            ret = EntityUtils.toString(resEntity);
            EntityUtils.consume(resEntity);
        }

    } catch (IOException e) {
        log.error("ERROR uploading File : ", e);
    }

    return ret;
}