List of usage examples for org.apache.http.client.fluent Content asString
public String asString()
From source file:com.mycompany.asyncreq.MainApp.java
public static void main(String[] args) throws InterruptedException, ExecutionException, IOException { URIBuilder builder = new URIBuilder(); builder.setScheme("http").setHost("comtrade.un.org").setPath("/api/get").setParameter("max", "50000") .setParameter("type", "C").setParameter("freq", "M").setParameter("px", "HS") .setParameter("ps", "2014").setParameter("r", "804").setParameter("p", "112") .setParameter("rg", "All").setParameter("cc", "All").setParameter("fmt", "json"); URI requestURL = null;/*from ww w . java2 s .co m*/ try { requestURL = builder.build(); } catch (URISyntaxException use) { } ExecutorService threadpool = Executors.newFixedThreadPool(2); Async async = Async.newInstance().use(threadpool); final Request request = Request.Get(requestURL); try { Future<Content> future = async.execute(request, new FutureCallback<Content>() { @Override public void failed(final Exception e) { System.out.println(e.getMessage() + ": " + request); } @Override public void completed(final Content content) { System.out.println("Request completed: " + request); System.out.println("Response:\n" + content.asString()); } @Override public void cancelled() { } }); } catch (Exception e) { System.out.println("Job threw exception: " + e.getCause()); } }
From source file:com.dianping.lion.api.http.SetConfigServlet.java
private void httpSetConfig(String querystr) throws IOException { String url = "http://lion-api-ppe01.hm:8080/setconfig?"; String query = querystr.replace("e=prelease", "e=product"); url = url + query;//from w ww .jav a2 s . c o m Content content = Request.Get(url).execute().returnContent(); String result = content.asString(); if (result.startsWith("0|")) { logger.info("set config to ppe: " + result); } else { String message = "failed to set config to ppe: " + result; logger.error(message); throw new RuntimeException(message); } }
From source file:junit.org.rapidpm.microservice.demo.ServletTest.java
@Test public void testServletGetReq002() throws Exception { final Content returnContent = Request.Get(url).execute().returnContent(); Assert.assertEquals("Hello World CDI Service", returnContent.asString()); // Request.Post("http://targethost/login") // .bodyForm(Form.form().add("username", "vip").add("password", "secret").build()) // .execute().returnContent(); }
From source file:conversandroid.pandora.PandoraConnection.java
/** * Sends the user message to the chatbot and returns the chatbot response * It is a simplification and adaptation to Android of the method with the same name in the * Pandorabots Java API: https://github.com/pandorabots/pb-java * @param input text for conversation/* w w w . java2s .c o m*/ * @return text of bot's response * @throws PandoraException when the connection is not succesful */ public String talk(String input) throws PandoraException { String responses = ""; input = input.replace(" ", "%20"); URI uri = null; try { uri = new URI("https://" + host + "/talk/" + appId + "/" + botName + "?input=" + input + "&user_key=" + userKey); Log.d(LOGTAG, "Request to pandorabot: Botname=" + botName + ", input=\"" + input + "\"" + " uri=" + uri); } catch (URISyntaxException e) { Log.e(LOGTAG, e.getMessage()); throw new PandoraException(PandoraErrorCode.IDORHOST); } int SDK_INT = android.os.Build.VERSION.SDK_INT; if (SDK_INT > 8) { StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); StrictMode.setThreadPolicy(policy); //Why the strictmode: http://stackoverflow.com/questions/25093546/android-os-networkonmainthreadexception-at-android-os-strictmodeandroidblockgua try { Content content = Request.Post(uri).execute().returnContent(); String response = content.asString(); JSONObject jObj = new JSONObject(response); JSONArray jArray = jObj.getJSONArray("responses"); for (int i = 0; i < jArray.length(); i++) { responses += jArray.getString(i).trim(); } } catch (JSONException e) { Log.e(LOGTAG, e.getMessage()); throw new PandoraException(PandoraErrorCode.PARSE); } catch (IOException e) { Log.e(LOGTAG, e.getMessage()); throw new PandoraException(PandoraErrorCode.CONNECTION); } catch (Exception e) { throw new PandoraException(PandoraErrorCode.IDORHOST); } } if (responses.toLowerCase().contains("match failed")) { Log.e(LOGTAG, "Match failed"); throw new PandoraException(PandoraErrorCode.NOMATCH); } Log.d(LOGTAG, "Bot response:" + responses); return responses; }
From source file:hudson.plugins.jira.JiraRestService.java
public List<Version> getVersions(String projectKey) { final URIBuilder builder = new URIBuilder(uri) .setPath(String.format("%s/project/%s/versions", baseApiPath, projectKey)); List<Map<String, Object>> decoded = Collections.emptyList(); try {/*from ww w . jav a 2 s . co m*/ URI uri = builder.build(); final Content content = buildGetRequest(uri).execute().returnContent(); decoded = objectMapper.readValue(content.asString(), new TypeReference<List<Map<String, Object>>>() { }); } catch (Exception e) { LOGGER.log(WARNING, "jira rest client get versions error. cause: " + e.getMessage(), e); } final List<Version> versions = new ArrayList<Version>(); for (Map<String, Object> decodedVersion : decoded) { final DateTime releaseDate = decodedVersion.containsKey("releaseDate") ? DATE_TIME_FORMATTER.parseDateTime((String) decodedVersion.get("releaseDate")) : null; final Version version = new Version(URI.create((String) decodedVersion.get("self")), Long.parseLong((String) decodedVersion.get("id")), (String) decodedVersion.get("name"), (String) decodedVersion.get("description"), (Boolean) decodedVersion.get("archived"), (Boolean) decodedVersion.get("released"), releaseDate); versions.add(version); } return versions; }
From source file:hudson.plugins.jira.JiraRestService.java
public List<Component> getComponents(String projectKey) { final URIBuilder builder = new URIBuilder(uri) .setPath(String.format("%s/project/%s/components", baseApiPath, projectKey)); try {/*w w w .j a v a 2 s . co m*/ final Content content = buildGetRequest(builder.build()).execute().returnContent(); final List<Map<String, Object>> decoded = objectMapper.readValue(content.asString(), new TypeReference<List<Map<String, Object>>>() { }); final List<Component> components = new ArrayList<Component>(); for (final Map<String, Object> decodeComponent : decoded) { BasicUser lead = null; if (decodeComponent.containsKey("lead")) { final Map<String, Object> decodedLead = (Map<String, Object>) decodeComponent.get("lead"); lead = new BasicUser(URI.create((String) decodedLead.get("self")), (String) decodedLead.get("name"), (String) decodedLead.get("displayName")); } final Component component = new Component(URI.create((String) decodeComponent.get("self")), Long.parseLong((String) decodeComponent.get("id")), (String) decodeComponent.get("name"), (String) decodeComponent.get("description"), lead); components.add(component); } return components; } catch (Exception e) { LOGGER.log(WARNING, "jira rest client process workflow action error. cause: " + e.getMessage(), e); return Collections.emptyList(); } }
From source file:gate.tagger.tagme.TaggerWatWS.java
protected String retrieveServerResponse(String text) { URI uri;//from w w w .j ava 2s .co m try { uri = new URIBuilder(getTagMeServiceUrl().toURI()).setParameter("text", text) .setParameter("gcube-token", getApiKey()).setParameter("lang", getLanguageCode()).build(); } catch (URISyntaxException ex) { throw new GateRuntimeException("Could not create URI for the request", ex); } //System.err.println("DEBUG: WAT URL="+uri); Request req = Request.Get(uri); Response res = null; try { res = req.execute(); } catch (Exception ex) { throw new GateRuntimeException("Problem executing HTTP request: " + req, ex); } Content cont = null; try { cont = res.returnContent(); } catch (Exception ex) { throw new GateRuntimeException("Problem getting HTTP response content: " + res, ex); } String ret = cont.asString(); logger.debug("WAT server response " + ret); return ret; }
From source file:gate.tagger.tagme.TaggerTagMeWS.java
protected String retrieveServerResponse(String text) { Request req = Request.Post(getTagMeServiceUrl().toString()); req.addHeader("Content-Type", "application/x-www-form-urlencoded"); req.bodyForm(//from w ww .j av a 2 s . c om Form.form().add("text", text).add("gcube-token", getApiKey()).add("lang", getLanguageCode()) .add("tweet", getIsTweet().toString()).add("include_abstract", "false") .add("include_categories", "false").add("include_all_spots", "false") .add("long_text", getLongText().toString()).add("epsilon", getEpsilon().toString()).build(), Consts.UTF_8); logger.debug("Request is " + req); Response res = null; try { res = req.execute(); } catch (Exception ex) { throw new GateRuntimeException("Problem executing HTTP request: " + req, ex); } Content cont = null; try { cont = res.returnContent(); } catch (Exception ex) { throw new GateRuntimeException("Problem getting HTTP response content: " + res, ex); } String ret = cont.asString(); logger.debug("TagMe server response " + ret); return ret; }
From source file:eu.trentorise.opendata.jackan.ckan.CkanClient.java
/** * * @param <T>// www . j av a 2 s .c o m * @param responseType a descendant of CkanResponse * @param path something like 1/api/3/action/package_create * @param body the body of the POST * @param the content type, i.e. * @param params list of key, value parameters. They must be not be url * encoded. i.e. "id","laghi-monitorati-trento" * @throws JackanException on error */ <T extends CkanResponse> T postHttp(Class<T> responseType, String path, String body, ContentType contentType, Object... params) { checkNotNull(responseType); checkNotNull(path); checkNotNull(body); checkNotNull(contentType); String fullUrl = calcFullUrl(path, params); try { logger.log(Level.FINE, "posting to url {0}", fullUrl); Request request = Request.Post(fullUrl); if (proxy != null) { request.viaProxy(proxy); } Response response = request.bodyString(body, contentType).addHeader("Authorization", ckanToken) .execute(); Content out = response.returnContent(); String json = out.asString(); T dr = getObjectMapper().readValue(json, responseType); if (!dr.success) { // monkey patching error type throw new JackanException("posting to catalog " + catalogURL + " was not successful. Reason: " + CkanError.read(getObjectMapper().readTree(json).get("error").asText())); } return dr; } catch (Exception ex) { throw new JackanException("Error while performing a POST! Request url is:" + fullUrl, ex); } }