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:com.vk.sdk.api.httpClient.VKHttpClient.java

public static HttpPost fileUploadRequest(String uploadUrl, File... files) {
    HttpPost post = new HttpPost(uploadUrl);
    post.setEntity(new VKMultipartEntity(files));
    return post;/*from   w w w.j  ava  2 s .  c o m*/
}

From source file:it.cloudicaro.disit.kb.rdf.HttpUtil.java

public static String post(URL url, String data, String contentType, String user, String passwd)
        throws Exception {
    //System.out.println("POST "+url);
    HttpClient client = HttpClients.createDefault();
    HttpPost request = new HttpPost(url.toURI());
    request.setEntity(new StringEntity(data, ContentType.create(contentType, "UTF-8")));

    HttpClientContext context = HttpClientContext.create();
    if (user != null && passwd != null) {
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(user, passwd));
        context.setCredentialsProvider(credsProvider);
    }/* w  ww.  ja  v  a2 s  .  c  o m*/

    HttpResponse response = client.execute(request, context);

    StatusLine s = response.getStatusLine();
    int code = s.getStatusCode();
    //System.out.println(code);
    if (code == 204)
        return "";
    if (code != 200)
        throw new Exception(
                "failed access to " + url.toString() + " code: " + code + " " + s.getReasonPhrase());

    Reader reader = null;
    try {
        reader = new InputStreamReader(response.getEntity().getContent());

        StringBuilder sb = new StringBuilder();
        {
            int read;
            char[] cbuf = new char[1024];
            while ((read = reader.read(cbuf)) != -1) {
                sb.append(cbuf, 0, read);
            }
        }

        return sb.toString();
    } finally {
        if (reader != null) {
            try {
                reader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

From source file:edu.isi.karma.util.HTTPUtil.java

public static String executeHTTPPostRequest(String serviceURL, String contentType, String acceptContentType,
        HttpEntity entity) throws ClientProtocolException, IOException {
    HttpPost httpPost = new HttpPost(serviceURL);
    httpPost.setEntity(entity);
    return invokeHTTPRequest(httpPost, contentType, acceptContentType);
}

From source file:com.appdynamics.openstack.nova.RestClient.java

static String doPost(String url, String entity, String token) throws Exception {
    HttpClient httpClient = httpClientWithTrustManager();
    StringEntity strEntity = new StringEntity(entity);
    strEntity.setContentType(jsonContentType);

    HttpPost post = new HttpPost(url);
    post.addHeader("accept", xmlContentType);
    post.setEntity(strEntity);

    if (token != null) {
        post.addHeader("X-Auth-Token", token);
    }/*from  ww  w.  j  a  v  a2  s  .co m*/

    HttpResponse response = httpClient.execute(post);

    return getResponseString(httpClient, response);

}

From source file:edu.isi.karma.util.HTTPUtil.java

public static String executeHTTPPostRequest(String serviceURL, String contentType, String acceptContentType,
        String rawPostBodyData) throws ClientProtocolException, IOException {

    // Prepare the headers
    HttpPost httpPost = new HttpPost(serviceURL);
    httpPost.setEntity(new StringEntity(rawPostBodyData));
    return invokeHTTPRequest(httpPost, contentType, acceptContentType);
}

From source file:net.locosoft.fold.neo4j.internal.Neo4jRestUtil.java

public static JsonObject doPostJson(String uri, JsonObject content) {
    try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) {
        HttpPost httpPost = new HttpPost(uri);
        httpPost.addHeader("Content-Type", "application/json");
        StringEntity stringEntity = new StringEntity(content.toString(), "UTF-8");
        httpPost.setEntity(stringEntity);
        CloseableHttpResponse response = httpClient.execute(httpPost);

        String bodyText = EntityUtils.toString(response.getEntity());
        JsonObject jsonObject = JsonObject.readFrom(bodyText);
        return jsonObject;
    } catch (Exception ex) {
        ex.printStackTrace();//from   w  w w. j a va2 s. c o  m
    }
    return null;
}

From source file:gov.nist.appvet.tool.sigverifier.util.ReportUtil.java

/** This method should be used for sending files back to AppVet. */
public static boolean sendInNewHttpRequest(String appId, String reportFilePath, ToolStatus reportStatus) {
    HttpParams httpParameters = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(httpParameters, 30000);
    HttpConnectionParams.setSoTimeout(httpParameters, 1200000);
    HttpClient httpClient = new DefaultHttpClient(httpParameters);
    httpClient = SSLWrapper.wrapClient(httpClient);

    try {/*ww w.ja v  a2  s  . com*/
        /*
         * To send reports back to AppVet, the following parameters must be
         * sent: - command: SUBMIT_REPORT - username: AppVet username -
         * password: AppVet password - appid: The app ID - toolid: The ID of
         * this tool - toolrisk: The risk assessment (LOW, MODERATE, HIGH,
         * ERROR) - report: The report file.
         */
        MultipartEntity entity = new MultipartEntity();
        entity.addPart("command", new StringBody("SUBMIT_REPORT", Charset.forName("UTF-8")));
        entity.addPart("username", new StringBody(Properties.appvetUsername, Charset.forName("UTF-8")));
        entity.addPart("password", new StringBody(Properties.appvetPassword, Charset.forName("UTF-8")));
        entity.addPart("appid", new StringBody(appId, Charset.forName("UTF-8")));
        entity.addPart("toolid", new StringBody(Properties.toolId, Charset.forName("UTF-8")));
        entity.addPart("toolrisk", new StringBody(reportStatus.name(), Charset.forName("UTF-8")));
        File report = new File(reportFilePath);
        FileBody fileBody = new FileBody(report);
        entity.addPart("file", fileBody);
        HttpPost httpPost = new HttpPost(Properties.appvetUrl);
        httpPost.setEntity(entity);
        // Send the report to AppVet
        log.debug("Sending report file to AppVet");
        final HttpResponse response = httpClient.execute(httpPost);
        log.debug("Received from AppVet: " + response.getStatusLine());
        HttpEntity httpEntity = response.getEntity();
        InputStream is = httpEntity.getContent();
        String result = IOUtils.toString(is, "UTF-8");
        log.info(result);
        // Clean up
        httpPost = null;
        return true;
    } catch (Exception e) {
        log.error(e.toString());
        return false;
    }
}

From source file:com.phoneToPc.Http.java

/**
 * Connects to the server,// ww w. j ava 2 s  .co m
 * @return String request response (or null)
 */

//CommandE 0 URL 
public static String httpReq(CommandE command) {

    final HttpResponse resp;
    String ResString = null;
    final ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
    assert (command.GetPropertyNum() >= 2);
    String url = command.GetProperty(1).GetPropertyContext();
    Log.d("HTTP", "httpReq : ");
    for (int i = 0; i < command.GetPropertyNum(); i++) {
        Log.d("HTTP",
                command.GetProperty(i).GetPropertyName() + " " + command.GetProperty(i).GetPropertyContext());
    }

    for (int i = 2; i < command.GetPropertyNum(); i++) {
        params.add(new BasicNameValuePair(command.GetProperty(i).GetPropertyName(),
                command.GetProperty(i).GetPropertyContext()));
    }

    final HttpEntity entity;
    try {
        entity = new UrlEncodedFormEntity(params, HTTP.UTF_8);
    } catch (final UnsupportedEncodingException e) {
        // this should never happen.
        throw new IllegalStateException(e);
    }
    Log.i(TAG, "connect url = " + url);
    final HttpPost post = new HttpPost(url);
    post.addHeader(entity.getContentType());
    post.setEntity(entity);
    try {
        resp = getHttpClient().execute(post);

        if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            InputStream istream = (resp.getEntity() != null) ? resp.getEntity().getContent() : null;
            if (istream != null) {
                BufferedReader ireader = new BufferedReader(new InputStreamReader(istream));
                ResString = ireader.readLine().trim();
                Log.e(TAG, "Http Resp = " + ResString);
            }
        } else {
            Log.e(TAG, "getStatusCode = " + resp.getStatusLine().getStatusCode());
        }

    } catch (final IOException e) {
        Log.e(TAG, "getHttpClient().execute(post)", e);
        return null;
    } finally {
        Log.v(TAG, "getAuthtoken completing");
    }

    return ResString;
}

From source file:org.opencastproject.remotetest.server.resource.SearchResources.java

public static HttpResponse add(TrustedHttpClient client, String mediapackage) throws Exception {
    HttpPost post = new HttpPost(getServiceUrl() + "add");
    List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
    params.add(new BasicNameValuePair("mediapackage", mediapackage));
    post.setEntity(new UrlEncodedFormEntity(params));
    return client.execute(post);
}

From source file:att.jaxrs.client.Content_tag.java

public static String addContent_tag(long content_id, long tag_id) {
    List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
    urlParameters.add(new BasicNameValuePair("content_id", Long.toString(content_id)));
    urlParameters.add(new BasicNameValuePair("tag_id", Long.toString(tag_id)));

    String resultStr = "";

    try {/*w ww  .  jav  a 2s.  c  o  m*/

        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost post = new HttpPost(Constants.INSERT_CONTENT_TAG_RESOURCE);
        post.setEntity(new UrlEncodedFormEntity(urlParameters));
        HttpResponse result = httpClient.execute(post);
        System.out.println(Constants.RESPONSE_STATUS_CODE + result);
        resultStr = Util.getStringFromInputStream(result.getEntity().getContent());
        System.out.println(Constants.RESPONSE_BODY + resultStr);

    } catch (Exception e) {
        System.out.println(e.getMessage());

    }
    return resultStr;
}