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:att.jaxrs.client.Content_tag.java

public static String deleteContent_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 {/*from   w w  w  . j a v a 2s  .com*/

        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost post = new HttpPost(Constants.DELETE_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;
}

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

public static String addTag(Tag tag) {
    final long tag_id = getExistingRecord(tag.getTag_name());
    if (-1L != tag_id) {
        return "{response:{Tag: 'EXISTING_RECORD'},tag_id:" + tag_id + "}";
    }//w ww.  ja  v a  2 s  .c  o  m
    List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
    urlParameters.add(new BasicNameValuePair("tag_name", tag.getTag_name()));

    HttpResponse result;
    String resultStr = "";

    try {

        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost post = new HttpPost(Constants.INSERT_TAG_RESOURCE);
        post.setEntity(new UrlEncodedFormEntity(urlParameters));
        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;
}

From source file:CB_Core.GCVote.GCVote.java

public static Boolean SendVotes(String User, String password, int vote, String url, String waypoint) {
    String guid = url.substring(url.indexOf("guid=") + 5).trim();

    String data = "userName=" + User + "&password=" + password + "&voteUser=" + String.valueOf(vote / 100.0)
            + "&cacheId=" + guid + "&waypoint=" + waypoint;

    try {/* www.j  a  v a2 s  .  c  o  m*/
        HttpPost httppost = new HttpPost("http://dosensuche.de/GCVote/setVote.php");

        httppost.setEntity(new ByteArrayEntity(data.getBytes("UTF8")));

        // Execute HTTP Post Request
        String responseString = Execute(httppost);

        return responseString.equals("OK\n");

    } catch (Exception ex) {
        return false;
    }

}

From source file:jsonclient.JsonClient.java

private static String postToURL(String url, String message, DefaultHttpClient httpClient)
        throws IOException, IllegalStateException, UnsupportedEncodingException, RuntimeException {
    HttpPost postRequest = new HttpPost(url);

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

    HttpResponse response = httpClient.execute(postRequest);

    if (response.getStatusLine().getStatusCode() != 200) {
        throw new RuntimeException("Failed : HTTP error code : " + response.getStatusLine().getStatusCode());
    }//from   w  ww .j  av a2  s . co m

    BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent())));

    String output;
    StringBuffer totalOutput = new StringBuffer();
    //System.out.println("Output from Server .... \n");
    while ((output = br.readLine()) != null) {
        //System.out.println(output);
        totalOutput.append(output);
    }
    return totalOutput.toString();
}

From source file:org.meruvian.midas.core.util.ConnectionUtil.java

public static JSONObject post(String url, List<NameValuePair> nameValuePairs) {
    JSONObject json = null;/* ww w. java  2 s  .c  o m*/
    try {
        HttpClient httpClient = new DefaultHttpClient(getHttpParams(TIMEOUT, TIMEOUT));
        HttpPost httpPost = new HttpPost(url);

        httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        HttpResponse response = httpClient.execute(httpPost);
        json = new JSONObject(convertEntityToString(response.getEntity()));
    } catch (IOException e) {
        json = null;
        e.printStackTrace();
    } catch (JSONException e) {
        json = null;
        e.printStackTrace();
    } catch (Exception e) {
        json = null;
        e.printStackTrace();
    }
    return json;
}

From source file:com.ibm.iot.iotspark.IoTPrediction.java

/**
 * Makes ReST call to the Predictive Analytics service with the given payload and responds with the predicted score.
 * /*w  ww  . j  a v  a 2  s.  co m*/
 * @param pURL
 * @param payload
 * @return
 * @throws ClientProtocolException
 * @throws IOException
 */
public static java.lang.String post(java.lang.String pURL, java.lang.String payload)
        throws ClientProtocolException, IOException {

    HttpClient client = new DefaultHttpClient();
    HttpPost post = new HttpPost(pURL);
    StringEntity input = new StringEntity(payload);
    input.setContentType("application/json");
    post.setEntity(input);

    HttpResponse response = client.execute(post);

    BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
    StringBuilder out = new StringBuilder();
    java.lang.String line;
    while ((line = rd.readLine()) != null) {
        //    System.out.println(line);
        out.append(line);
    }

    System.out.println(out.toString()); //Prints the string content read from input stream
    rd.close();
    return out.toString();
}

From source file:org.energyos.espi.datacustodian.console.ImportUsagePoint.java

public static void upload(String filename, String url, HttpClient client) throws IOException {
    HttpPost post = new HttpPost(url);
    MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

    File file = new File(filename);
    entity.addPart("file", new FileBody(((File) file), "application/rss+xml"));

    post.setEntity(entity);

    client.execute(post);/*from   w  ww. j a  v a2 s .co m*/
}

From source file:eu.trentorise.smartcampus.ac.network.RemoteConnector.java

/**
 * @param string/* ww w .  ja  va 2  s. c om*/
 * @param refresh
 * @param clientId
 * @param clientSecret
 * @throws AACException 
 */
public static TokenData refreshToken(String service, String refresh, String clientId, String clientSecret)
        throws AACException {
    HttpResponse resp = null;
    HttpEntity entity = null;
    Log.i(TAG, "refreshing token: " + refresh);
    String url = service + PATH_TOKEN + "?grant_type=refresh_token&refresh_token=" + refresh + "&client_id="
            + clientId + "&client_secret=" + clientSecret;
    HttpPost post = new HttpPost(url);
    post.setEntity(entity);
    post.setHeader("Accept", "application/json");
    try {
        resp = getHttpClient().execute(post);
        String response = EntityUtils.toString(resp.getEntity());
        if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            TokenData data = TokenData.valueOf(response);
            Log.v(TAG, "Successful authentication");
            return data;
        }
        Log.e(TAG, "Error validating " + resp.getStatusLine());
        try {
            JSONObject error = new JSONObject(response);
            if (error != null && error.has("error")) {
                throw new AACException(HttpStatus.SC_UNAUTHORIZED,
                        "OAuth error " + error.optString("error_description"));
            }
        } catch (JSONException e) {
            Log.w(TAG, "Unknown response message:" + resp.getStatusLine());
        }
        throw new AACException("Error validating " + resp.getStatusLine());

        //        } catch (Exception e) {
        //            Log.e(TAG, "Exception when getting authtoken", e);
        //            if (resp != null) {
        //               throw new AACException(resp.getStatusLine().getStatusCode(), ""+e.getMessage());
        //            } else {
        //               throw new AACException(e);
        //            }
    } catch (ClientProtocolException e) {
        if (resp != null) {
            throw new AACException(resp.getStatusLine().getStatusCode(), "" + e.getMessage());
        } else {
            throw new AACException(e);
        }
    } catch (IOException e) {
        if (resp != null) {
            throw new AACException(resp.getStatusLine().getStatusCode(), "" + e.getMessage());
        } else {
            throw new AACException(e);
        }
    } finally {
        Log.v(TAG, "refresh token completing");
    }
}

From source file:apidemo.APIDemo.java

public static String sendPostJson(String postUrl, String jsonContent, int timeout /*milisecond*/)
        throws Exception {
    RequestConfig defaultRequestConfig = RequestConfig.custom().setSocketTimeout(timeout)
            .setConnectTimeout(timeout).build();
    try (CloseableHttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(defaultRequestConfig)
            .build()) {/*from  w w  w.  j  av  a 2s .co m*/
        HttpPost httpPost = new HttpPost(postUrl);
        StringEntity input = new StringEntity(jsonContent, "UTF-8");
        input.setContentType("application/json");
        httpPost.setEntity(input);
        try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
            if (response.getStatusLine().getStatusCode() != 200) {
                throw new IOException("Failed : HTTP getStatusCode: " + response.getStatusLine().getStatusCode()
                        + " HTTP getReasonPhrase: " + response.getStatusLine().getReasonPhrase());
            }
            try (BufferedReader br = new BufferedReader(
                    new InputStreamReader((response.getEntity().getContent())))) {
                String output;
                StringBuilder strBuilder = new StringBuilder();
                while ((output = br.readLine()) != null) {
                    strBuilder.append(output);
                }
                return strBuilder.toString();
            }
        }
    }
}

From source file:com.mycompany.trader.HTTPTransport.java

public static HttpPost createPost(String resource, String data) {
    try {/*from   w  w  w .j  av  a2  s  . co m*/
        HttpPost post = new HttpPost(url + resource);
        StringEntity input = new StringEntity(data);
        input.setContentType("application/json");
        post.setEntity(input);
        return post;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}