List of usage examples for org.apache.http.client.methods HttpPost toString
public String toString()
From source file:com.gemstone.gemfire.rest.internal.web.controllers.RestAPITestBase.java
protected CloseableHttpResponse executeFunctionThroughRestCall(String function, String regionName, String filter, String jsonBody, String groups, String members) { LogWriterUtils.getLogWriter().info("Entering executeFunctionThroughRestCall"); try {// ww w .j a v a 2s . c o m CloseableHttpClient httpclient = HttpClients.createDefault(); Random randomGenerator = new Random(); int restURLIndex = randomGenerator.nextInt(restURLs.size()); HttpPost post = createHTTPPost(function, regionName, filter, restURLIndex, groups, members, jsonBody); LogWriterUtils.getLogWriter().info("Request: POST " + post.toString()); return httpclient.execute(post); } catch (Exception e) { throw new RuntimeException("unexpected exception", e); } }
From source file:com.vsct.dt.hesperides.feedback.FeedbacksAggregate.java
@Override public void sendFeedbackToHipchat(final User user, final FeedbackJson template) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("Feedback from " + user.getUsername() + " to hipchat room\n" + template.toJsonString()); }//w w w . j a v a 2s . co m final String imageData = template.getFeedback().getImg().split(",")[1]; final String imageName = String.format("feedback_%s.png", template.getFeedback().getTimestamp()); try { final String applicationPath; final Iterator<Map.Entry<String, String>> itOverride = assetsConfiguration.getOverrides().iterator(); if (itOverride.hasNext()) { applicationPath = itOverride.next().getValue(); } else { throw new HesperidesException("Could not create Feedback: asserts configuration not valid"); } LOGGER.debug("Server path : {}", applicationPath); writeImage(getServerPathImageName(applicationPath, imageName), imageData); CloseableHttpClient httpClient = getHttpClient(); HttpPost postRequest = new HttpPost(getHipchatUrl()); StringEntity input = new StringEntity(getHipchatMessageBody(template, imageName, user)); input.setContentType("application/json"); postRequest.setEntity(input); // LOG if (LOGGER.isDebugEnabled()) { LOGGER.debug("------------- Post send Hipchat request ------------------------------------------"); LOGGER.debug(postRequest.toString()); LOGGER.debug("------------- Post send Hipchat content request ---------------------------------"); LOGGER.debug(getStringContent(postRequest.getEntity())); } HttpResponse postResponse = httpClient.execute(postRequest); // LOG LOGGER.debug("------------- Post send Hipchat response ------------------------------------------"); LOGGER.debug(postResponse.toString()); if (postResponse.getStatusLine().getStatusCode() != 204) { throw new RuntimeException( "Failed : HTTP error code : " + postResponse.getStatusLine().getStatusCode()); } } catch (IOException e) { e.printStackTrace(); } }
From source file:org.megam.deccanplato.http.TransportMachinery.java
public static TransportResponse post(TransportTools nuts) throws ClientProtocolException, IOException { DefaultHttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost(nuts.urlString()); System.out.println("NUTS" + nuts.toString()); if (nuts.headers() != null) { for (Map.Entry<String, String> headerEntry : nuts.headers().entrySet()) { //this if condition is set for twilio Rest API to add credentials to DefaultHTTPClient, conditions met twilio work. if (headerEntry.getKey().equalsIgnoreCase("provider") & headerEntry.getValue().equalsIgnoreCase(nuts.headers().get("provider"))) { httpclient.getCredentialsProvider().setCredentials( new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT), new UsernamePasswordCredentials( nuts.headers().get("account_sid"), nuts.headers().get("oauth_token"))); }/* w ww . j a v a2s . co m*/ //this else part statements for other providers else { httppost.addHeader(headerEntry.getKey(), headerEntry.getValue()); } } } if (nuts.fileEntity() != null) { httppost.setEntity(nuts.fileEntity()); } if (nuts.pairs() != null && (nuts.contentType() == null)) { httppost.setEntity(new UrlEncodedFormEntity(nuts.pairs())); } if (nuts.contentType() != null) { httppost.setEntity(new StringEntity(nuts.contentString(), nuts.contentType())); } TransportResponse transportResp = null; System.out.println(httppost.toString()); try { HttpResponse httpResp = httpclient.execute(httppost); transportResp = new TransportResponse(httpResp.getStatusLine(), httpResp.getEntity(), httpResp.getLocale()); } finally { httppost.releaseConnection(); } return transportResp; }
From source file:org.syncany.cli.CommandLineClient.java
private int sendToRest(Command command, String commandName, String[] commandArgs, File portFile) { try {//w w w .j a va2 s . com // Read port config (for daemon) from port file PortTO portConfig = readPortConfig(portFile); // Create authentication details CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(new AuthScope(SERVER_HOSTNAME, portConfig.getPort()), new UsernamePasswordCredentials(portConfig.getUser().getUsername(), portConfig.getUser().getPassword())); // Allow all hostnames in CN; this is okay as long as hostname is localhost/127.0.0.1! // See: https://github.com/syncany/syncany/pull/196#issuecomment-52197017 X509HostnameVerifier hostnameVerifier = new AllowAllHostnameVerifier(); // Fetch the SSL context (using the user key/trust store) SSLContext sslContext = UserConfig.createUserSSLContext(); // Create client with authentication details CloseableHttpClient client = HttpClients.custom().setSslcontext(sslContext) .setHostnameVerifier(hostnameVerifier).setDefaultCredentialsProvider(credentialsProvider) .build(); // Build and send request, print response Request request = buildFolderRequestFromCommand(command, commandName, commandArgs, config.getLocalDir().getAbsolutePath()); String serverUri = SERVER_SCHEMA + SERVER_HOSTNAME + ":" + portConfig.getPort() + SERVER_REST_API; String xmlMessageString = XmlMessageFactory.toXml(request); StringEntity xmlMessageEntity = new StringEntity(xmlMessageString); HttpPost httpPost = new HttpPost(serverUri); httpPost.setEntity(xmlMessageEntity); logger.log(Level.INFO, "Sending HTTP Request to: " + serverUri); logger.log(Level.FINE, httpPost.toString()); logger.log(Level.FINE, xmlMessageString); HttpResponse httpResponse = client.execute(httpPost); int exitCode = handleRestResponse(command, httpResponse); return exitCode; } catch (Exception e) { logger.log(Level.SEVERE, "Command " + command.toString() + " FAILED. ", e); return showErrorAndExit(e.getMessage()); } }
From source file:org.apache.streams.graph.GraphPersistWriter.java
@Override protected ObjectNode executePost(HttpPost httpPost) { Preconditions.checkNotNull(httpPost); ObjectNode result = null;/*from w w w.j a va 2 s .c om*/ CloseableHttpResponse response = null; String entityString = null; try { response = httpclient.execute(httpPost); HttpEntity entity = response.getEntity(); if (response.getStatusLine().getStatusCode() == 200 || response.getStatusLine().getStatusCode() == 201 && entity != null) { entityString = EntityUtils.toString(entity); result = mapper.readValue(entityString, ObjectNode.class); } LOGGER.debug("Writer response:\n{}\n{}\n{}", httpPost.toString(), response.getStatusLine().getStatusCode(), entityString); if (result == null || (result.get("errors") != null && result.get("errors").isArray() && result.get("errors").iterator().hasNext())) { LOGGER.error("Write Error: " + result.get("errors")); } else { LOGGER.info("Write Success"); } } catch (IOException e) { LOGGER.error("IO error:\n{}\n{}\n{}", httpPost.toString(), response, e.getMessage()); } catch (Exception e) { LOGGER.error("Write Exception:\n{}\n{}\n{}", httpPost.toString(), response, e.getMessage()); } finally { try { if (response != null) response.close(); } catch (IOException e) { } } return result; }
From source file:org.apache.streams.graph.GraphHttpPersistWriter.java
@Override protected ObjectNode executePost(HttpPost httpPost) { Objects.requireNonNull(httpPost); ObjectNode result = null;/*from www.j a v a 2s . c o m*/ CloseableHttpResponse response = null; String entityString = null; try { response = httpclient.execute(httpPost); HttpEntity entity = response.getEntity(); if (response.getStatusLine().getStatusCode() == 200 || response.getStatusLine().getStatusCode() == 201 && entity != null) { entityString = EntityUtils.toString(entity); result = mapper.readValue(entityString, ObjectNode.class); } LOGGER.debug("Writer response:\n{}\n{}\n{}", httpPost.toString(), response.getStatusLine().getStatusCode(), entityString); if (result == null || (result.get("errors") != null && result.get("errors").isArray() && result.get("errors").iterator().hasNext())) { LOGGER.error("Write Error: " + result.get("errors")); } else { LOGGER.debug("Write Success"); } } catch (IOException ex) { LOGGER.error("IO error:\n{}\n{}\n{}", httpPost.toString(), response, ex.getMessage()); } catch (Exception ex) { LOGGER.error("Write Exception:\n{}\n{}\n{}", httpPost.toString(), response, ex.getMessage()); } finally { try { if (response != null) { response.close(); } } catch (IOException ignored) { LOGGER.trace("ignored IOException", ignored); } } return result; }
From source file:net.dataninja.oracle.client.DataNinjaHttpClient.java
public String fetchSmartSentimentRdf(String text, String url, int maxSize) { String output = ""; try {/* w w w. j av a 2s .com*/ HttpClient client = getHttpClient(); HttpPost postRequest = new HttpPost(config.getApiUrl() + "/smartsentiment/tagentityrdf"); DataNinjaInput dataNinjaInput = new DataNinjaInput(); dataNinjaInput.setText(text); dataNinjaInput.setUrl(url); dataNinjaInput.setMax_size(maxSize); System.out.println(dataNinjaInput.toJsonString()); StringEntity entity = new StringEntity(dataNinjaInput.toJsonString()); entity.setContentType("application/json"); postRequest.setEntity(entity); // Add additional header to postRequest which accepts application/json data postRequest.addHeader("accept", "application/json"); postRequest.addHeader("X-Mashape-Key", config.getMashapeKey()); System.out.println(postRequest.toString()); // Execute the POST request and catch response HttpResponse response = client.execute(postRequest); // Check for HTTP response code: 200 = success if (response.getStatusLine().getStatusCode() != 200) { System.out.printf(response.toString()); throw new RuntimeException( "Failed : HTTP error code : " + response.getStatusLine().getStatusCode()); } // Get-Capture Complete the RDF body response BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent()))); StringBuffer sb = new StringBuffer(); String line; // Simply iterate through RDF response and show on console. while ((line = br.readLine()) != null) { sb.append(line).append("\n"); // System.out.println(line); } output = sb.toString(); } catch (ClientProtocolException e) { System.out.println("Problem fetching RDF content"); e.printStackTrace(); } catch (IOException e) { System.out.println("Problem fetching RDF content"); e.printStackTrace(); } catch (UnrecoverableKeyException e) { System.out.println("Problem fetching RDF content"); e.printStackTrace(); } catch (NoSuchAlgorithmException e) { System.out.println("Problem fetching RDF content"); e.printStackTrace(); } catch (KeyStoreException e) { System.out.println("Problem fetching RDF content"); e.printStackTrace(); } catch (KeyManagementException e) { System.out.println("Problem fetching RDF content"); e.printStackTrace(); } return output; }
From source file:org.apache.streams.components.http.persist.SimpleHTTPPostPersistWriter.java
protected ObjectNode executePost(HttpPost httpPost) { Objects.requireNonNull(httpPost); ObjectNode result = null;//from w ww.j a va 2s .c o m CloseableHttpResponse response = null; String entityString; try { response = httpclient.execute(httpPost); HttpEntity entity = response.getEntity(); // TODO: handle retry if (response.getStatusLine() != null && response.getStatusLine().getStatusCode() >= HttpStatus.SC_OK && entity != null) { entityString = EntityUtils.toString(entity); result = mapper.readValue(entityString, ObjectNode.class); } } catch (IOException ex) { LOGGER.error("IO error:\n{}\n{}\n{}", httpPost.toString(), response, ex.getMessage()); } finally { try { if (response != null) { response.close(); } } catch (IOException ignored) { LOGGER.trace("IOException", ignored); } } return result; }
From source file:com.urs.triptracks.TripUploader.java
boolean uploadOneTrip(long currentTripId) { boolean result = false; String postBodyData;//w w w .j a v a 2 s . c o m try { postBodyData = getPostData(currentTripId); } catch (JSONException e) { e.printStackTrace(); return result; } Log.v("codedPostData", postBodyData); HttpClient client = new DefaultHttpClient(); //final String postUrl = "https://fdotrts.ursokr.com/TripTracker_WCF_Rest_Service_ursokr/TripTracker.svc/SaveTrip"; final String postUrl1 = "https://fdotrts.ursokr.com/TripTracker_WCF_Rest_Service_ursokr/TripTracker.svc/OpenConnTest"; HttpGet postRequest1 = new HttpGet(postUrl1); Log.v("PostURLOPENCONN:", postUrl1); Log.v("PostURLOPENCONN:", postRequest1.toString()); postRequest1.setHeader("Accept", "application/json"); postRequest1.setHeader("Content-type", "application/json; charset=utf-8"); try { StringEntity str1 = new StringEntity(postBodyData, HTTP.UTF_8); //postRequest1.setEntity(str1); HttpResponse response1 = client.execute(postRequest1); HttpEntity entity1 = response1.getEntity(); String responseString1 = getASCIIContentFromEntity(entity1); Log.v("httpResponseHema1", responseString1); JSONObject responseData1 = new JSONObject(responseString1); Log.v("responseDataHema1:", responseData1.toString()); /*if (responseData.getString("Result").equals("Trip data was saved")) { mDb.open(); mDb.updateTripStatus(currentTripId, TripData.STATUS_SENT); mDb.close(); result = true; }*/ //if (responseData1.getString("Result").equals("Web service contacted and responded")) { if (responseData1.getString("Result") .startsWith(" Success connecting to the database via the webservice")) { final String postUrl2 = "https://fdotrts.ursokr.com/TripTracker_WCF_Rest_Service_ursokr/TripTracker.svc/SaveTrip"; HttpPost postRequest2 = new HttpPost(postUrl2); Log.v("PostURL2:", postUrl2); Log.v("PostRequest2:", postRequest2.toString()); postRequest2.setHeader("Accept", "application/json"); postRequest2.setHeader("Content-type", "application/json; charset=utf-8"); try { Log.v("postBodyData:", postBodyData); StringEntity str2 = new StringEntity(postBodyData, HTTP.UTF_8); postRequest2.setEntity(str2); HttpResponse response2 = client.execute(postRequest2); HttpEntity entity2 = response2.getEntity(); String responseString2 = getASCIIContentFromEntity(entity2); Log.v("httpResponseHema2", responseString2); JSONObject responseData2 = new JSONObject(responseString2); Log.v("responseDataHema2:", responseData2.toString()); if (responseData2.getString("Result").equals("Trip data was saved")) { mDb.open(); mDb.updateTripStatus(currentTripId, TripData.STATUS_SENT); mDb.close(); result = true; } } catch (IllegalStateException e) { e.printStackTrace(); return false; } catch (IOException e) { e.printStackTrace(); return false; } catch (JSONException e) { e.printStackTrace(); Log.e("Hema_log_tag2nd", "Error parsing data " + e.toString()); Log.e("Hema_log_tag2nd", "Failed data was:\n" + result); return false; } return result; } else { Toast.makeText(mCtx.getApplicationContext(), "Couldn't connect to the webservice.", Toast.LENGTH_LONG).show(); } } catch (IllegalStateException e) { e.printStackTrace(); return false; } catch (IOException e) { e.printStackTrace(); return false; } catch (JSONException e) { e.printStackTrace(); Log.e("Hema_log_tag1st", "1st step Error parsing data " + e.toString()); Log.e("Hema_log_tag1st", "1st step Failed data was:\n" + result); return false; } return result; }
From source file:com.couchbase.jdbc.core.ProtocolImpl.java
public CouchResponse doQuery(String query, Map queryParameters) throws SQLException { Instance endPoint = getNextEndpoint(); // keep trying endpoints while (true) { try {/* w w w.ja v a 2s .co m*/ String url = endPoint.getEndpointURL(ssl); logger.trace("Using endpoint {}", url); HttpPost httpPost = new HttpPost(url); httpPost.setHeader("Accept", "application/json"); logger.trace("do query {}", httpPost.toString()); addOptions(queryParameters); String jsonParameters = JsonFactory.toJson(queryParameters); StringEntity entity = new StringEntity(jsonParameters, ContentType.APPLICATION_JSON); httpPost.setEntity(entity); CloseableHttpResponse response = httpClient.execute(httpPost); return handleResponse(query, response); } catch (ConnectTimeoutException cte) { logger.trace(cte.getLocalizedMessage()); // this one failed, lets move on invalidateEndpoint(endPoint); // get the next one endPoint = getNextEndpoint(); if (endPoint == null) { throw new SQLException("All endpoints have failed, giving up"); } } catch (Exception ex) { logger.error("Error executing query [{}] {}", query, ex.getMessage()); throw new SQLException("Error executing update", ex); } } }