List of usage examples for org.apache.http.client.methods HttpPost setEntity
public void setEntity(final HttpEntity entity)
From source file:com.netflix.raigad.utils.SystemUtils.java
public static String runHttpPostCommand(String url, String jsonBody) throws IOException { String return_; DefaultHttpClient client = new DefaultHttpClient(); InputStream isStream = null;//from www . j ava 2 s . c om try { HttpParams httpParameters = new BasicHttpParams(); int timeoutConnection = 1000; int timeoutSocket = 1000; HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection); HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket); client.setParams(httpParameters); HttpPost postRequest = new HttpPost(url); if (StringUtils.isNotEmpty(jsonBody)) postRequest.setEntity(new StringEntity(jsonBody, StandardCharsets.UTF_8)); postRequest.setHeader("Content-type", "application/json"); HttpResponse resp = client.execute(postRequest); if (resp == null || resp.getEntity() == null) { throw new ESHttpException("Unable to execute POST URL (" + url + ") Exception Message: < Null Response or Null HttpEntity >"); } isStream = resp.getEntity().getContent(); if (resp.getStatusLine().getStatusCode() != 200) { throw new ESHttpException("Unable to execute POST URL (" + url + ") Exception Message: (" + IOUtils.toString(isStream, StandardCharsets.UTF_8.toString()) + ")"); } return_ = IOUtils.toString(isStream, StandardCharsets.UTF_8.toString()); logger.debug("POST URL API: {} with JSONBody {} returns: {}", url, jsonBody, return_); } catch (Exception e) { throw new ESHttpException( "Caught an exception during execution of URL (" + url + ")Exception Message: (" + e + ")"); } finally { if (isStream != null) isStream.close(); } return return_; }
From source file:core.VirusTotalAPIHelper.java
public static CloseableHttpResponse reScan(String sha256) { try {//from ww w . j ava2s . co m CloseableHttpClient client = HttpClients.createDefault(); HttpPost httpsScanFilePost = new HttpPost(httpsPost + "file/rescan"); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.addTextBody("apikey", apiKey); builder.addTextBody("resource", sha256); 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:core.VirusTotalAPIHelper.java
public static CloseableHttpResponse getReport(String sha256) { try {/*from w w w. ja va 2 s . c om*/ CloseableHttpClient client = HttpClients.createDefault(); HttpPost httpsScanFilePost = new HttpPost(httpsPost + "file/report"); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.addTextBody("apikey", apiKey); builder.addTextBody("resource", sha256); 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:com.lagrange.LabelApp.java
/** * Try to send message with labels and its probabilities to telegram *//* w w w. j av a2 s . c o m*/ private static void sendMessageToTelegramBot(List<EntityAnnotation> labels) throws IOException { String urlSendMessage = "https://api.telegram.org/" + BOT_ID + "/sendMessage"; CloseableHttpClient httpclient = HttpClients.createDefault(); HttpPost httpPost = new HttpPost(urlSendMessage); List<NameValuePair> nvps = new ArrayList<>(); nvps.add(new BasicNameValuePair("text", buildMessage(labels))); nvps.add(new BasicNameValuePair("chat_id", CHAT_ID)); httpPost.setEntity(new UrlEncodedFormEntity(nvps)); CloseableHttpResponse response = httpclient.execute(httpPost); try { System.out.println(response.getStatusLine()); } finally { response.close(); } System.out.println("Done sending text"); }
From source file:com.zxy.commons.httpclient.HttpclientUtils.java
/** * Post url/*from w ww .j a v a2 s.c o m*/ * * @param connectTimeoutSec () * @param socketTimeoutSec ??() * @param url url? * @param params {@link org.apache.http.NameValuePair} params * <p> * example:{@code params.add(new BasicNameValuePair("id", "123456"));} * @return post?? * @throws ClientProtocolException ClientProtocolException * @throws IOException IOException * @see org.apache.http.NameValuePair * @see org.apache.http.message.BasicNameValuePair */ public static String post(int connectTimeoutSec, int socketTimeoutSec, String url, List<NameValuePair> params) throws ClientProtocolException, IOException { CloseableHttpClient httpClient = null; CloseableHttpResponse httpResponse = null; try { // httpClient = HttpClients.createDefault(); RequestConfig config = RequestConfig.custom().setConnectTimeout(connectTimeoutSec * 1000) .setConnectionRequestTimeout(connectTimeoutSec * 1000).setSocketTimeout(socketTimeoutSec * 1000) .build(); httpClient = HttpClientBuilder.create().setDefaultRequestConfig(config).build(); HttpPost httppost = new HttpPost(url); UrlEncodedFormEntity uefEntity = new UrlEncodedFormEntity(params, Charsets.UTF_8); httppost.setEntity(uefEntity); httpResponse = httpClient.execute(httppost); HttpEntity entity = httpResponse.getEntity(); return EntityUtils.toString(entity, Charsets.UTF_8); } finally { HttpClientUtils.closeQuietly(httpResponse); HttpClientUtils.closeQuietly(httpClient); } }
From source file:net.modelbased.proasense.storage.registry.RegisterSensorSSN.java
public static String postSensor(Sensor sensor) throws RequestErrorException { String content = JsonPrinter.sensorToJson(sensor); URI target;//from ww w .j a v a 2s .co m try { target = new URI(sensor.getUri().toString() + SENSOR_PATH); } catch (URISyntaxException e1) { e1.printStackTrace(); throw new RequestErrorException(e1.getMessage()); } HttpClient client = new DefaultHttpClient(); HttpPost request = new HttpPost(target); request.setHeader("Content-type", "application/json"); String response = null; try { StringEntity seContent = new StringEntity(content); seContent.setContentType("text/json"); request.setEntity(seContent); response = resolveResponse(client.execute(request)); } catch (Exception e) { throw new RequestErrorException(e.getMessage()); } return response; }
From source file:com.android.feedmeandroid.HTTPClient.java
public static ArrayList<JSONObject> SendHttpPost(String URL, JSONObject jsonObjSend) { try {// www.j ava 2 s. co m ArrayList<JSONObject> retArray = new ArrayList<JSONObject>(); DefaultHttpClient httpclient = new DefaultHttpClient(); HttpPost httpPostRequest = new HttpPost(URL); StringEntity se; se = new StringEntity(jsonObjSend.toString()); // Set HTTP parameters httpPostRequest.setEntity(se); httpPostRequest.setHeader("Accepts", "application/json"); httpPostRequest.setHeader("Content-Type", "application/json"); // httpPostRequest.setHeader("Accept-Encoding", "gzip"); // only set // this parameter if you would like to use gzip compression long t = System.currentTimeMillis(); HttpResponse response = (HttpResponse) httpclient.execute(httpPostRequest); Log.v(TAG, "HTTPResponse received in [" + (System.currentTimeMillis() - t) + "ms]"); // Get hold of the response entity (-> the data): HttpEntity entity = response.getEntity(); if (entity != null) { // Read the content stream InputStream instream = entity.getContent(); Header contentEncoding = response.getFirstHeader("Content-Encoding"); if (contentEncoding != null && contentEncoding.getValue().equalsIgnoreCase("gzip")) { instream = new GZIPInputStream(instream); } // convert content stream to a String String resultString = convertStreamToString(instream); Log.i(TAG, resultString); instream.close(); resultString = resultString.substring(1, resultString.length() - 2); // remove wrapping "[" and // "]" String[] results = resultString.split("\\},\\{"); for (int i = 0; i < results.length; i++) { JSONObject jsonObjRecv; String res = results[i]; // Transform the String into a JSONObject if (i == 0 && results.length > 1) { jsonObjRecv = new JSONObject(res + "}"); } else if (i == results.length - 1 && results.length > 1) { jsonObjRecv = new JSONObject("{" + res); } else { jsonObjRecv = new JSONObject("{" + res + "}"); } retArray.add(jsonObjRecv); // Raw DEBUG output of our received JSON object: Log.i(TAG, "<JSONObject>\n" + jsonObjRecv.toString() + "\n</JSONObject>"); } return retArray; } } catch (Exception e) { // More about HTTP exception handling in another tutorial. // For now we just print the stack trace. e.printStackTrace(); } return null; }
From source file:com.wbtech.ums.common.NetworkUitlity.java
public static MyMessage post(String url, String data) { // TODO Auto-generated method stub CommonUtil.printLog("ums", url); String returnContent = ""; MyMessage message = new MyMessage(); HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost(url); try {/*w w w . ja va2 s. c om*/ StringEntity se = new StringEntity("content=" + data, HTTP.UTF_8); CommonUtil.printLog("postdata", "content=" + data); se.setContentType("application/x-www-form-urlencoded"); httppost.setEntity(se); HttpResponse response = httpclient.execute(httppost); int status = response.getStatusLine().getStatusCode(); CommonUtil.printLog("ums", status + ""); String returnXML = EntityUtils.toString(response.getEntity()); returnContent = URLDecoder.decode(returnXML); switch (status) { case 200: message.setFlag(true); message.setMsg(returnContent); break; default: Log.e("error", status + returnContent); message.setFlag(false); message.setMsg(returnContent); break; } } catch (Exception e) { JSONObject jsonObject = new JSONObject(); try { jsonObject.put("err", e.toString()); returnContent = jsonObject.toString(); message.setFlag(false); message.setMsg(returnContent); } catch (JSONException e1) { e1.printStackTrace(); } } CommonUtil.printLog("UMSAGENT", message.getMsg()); return message; }
From source file:hackathon.women.challengeme.ServerUtilities.java
/** * Issue a POST request to the server./*from ww w . j av a2 s . co m*/ * * @param endpoint POST address. * @param params request parameters. * * @throws IOException propagated from POST. */ private static void post(String endpoint, List<NameValuePair> params) throws IOException { // Create a new HttpClient and Post Header HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost(endpoint); try { // Add your data httppost.setEntity(new UrlEncodedFormEntity(params)); // Execute HTTP Post Request HttpResponse response = httpclient.execute(httppost); int status = response.getStatusLine().getStatusCode(); if (status != 200) { Log.i("MyChallenge", "POST to server failed with error code" + status); } } catch (ClientProtocolException e) { // TODO Auto-generated catch block } catch (IOException e) { // TODO Auto-generated catch block } }
From source file:org.sead.repositories.reference.util.SEADAuthenticator.java
static public HttpClientContext authenticate(String server) { boolean authenticated = false; log.info("Authenticating"); String accessToken = SEADGoogleLogin.getAccessToken(); // Now login to server and create a session CloseableHttpClient httpclient = HttpClients.createDefault(); try {/*from ww w. ja va 2s. com*/ // //DoLogin is the auth endpoint when using the AUthFilter, versus // the api/authenticate endpoint when connecting to the ACR directly HttpPost seadAuthenticate = new HttpPost(server + "/DoLogin"); List<NameValuePair> nvpList = new ArrayList<NameValuePair>(1); nvpList.add(0, new BasicNameValuePair("googleAccessToken", accessToken)); seadAuthenticate.setEntity(new UrlEncodedFormEntity(nvpList)); CloseableHttpResponse response = httpclient.execute(seadAuthenticate, localContext); try { if (response.getStatusLine().getStatusCode() == 200) { HttpEntity resEntity = response.getEntity(); if (resEntity != null) { // String seadSessionId = // EntityUtils.toString(resEntity); authenticated = true; } } else { // Seems to occur when google device id is not set on server // - with a Not Found response... log.error("Error response from " + server + " : " + response.getStatusLine().getReasonPhrase()); } } finally { response.close(); httpclient.close(); } } catch (IOException e) { log.error("Cannot read sead-google.json"); log.error(e.getMessage()); } // localContext should have the cookie with the SEAD session key, which // nominally is all that's needed. // FixMe: If there is no activity for more than 15 minutes, the session // may expire, in which case, // re-authentication using the refresh token to get a new google token // to allow SEAD login again may be required // also need to watch the 60 minutes google token timeout - project // spaces will invalidate the session at 60 minutes even if there is // activity authTime = System.currentTimeMillis(); if (authenticated) { return localContext; } return null; }