List of usage examples for org.apache.commons.httpclient HttpMethod getResponseBodyAsStream
public abstract InputStream getResponseBodyAsStream() throws IOException;
From source file:arena.httpclient.commons.JakartaCommonsHttpClient.java
private byte[] getResponseBytes(HttpMethod method) throws IOException { InputStream responseStream = null; ByteArrayOutputStream stash = new ByteArrayOutputStream(); try {/*from ww w . j av a 2 s . co m*/ responseStream = method.getResponseBodyAsStream(); byte buffer[] = new byte[1024]; int read = 0; while ((read = responseStream.read(buffer)) != -1) { stash.write(buffer, 0, read); } return stash.toByteArray(); } finally { stash.close(); if (responseStream != null) { try { responseStream.close(); } catch (IOException err) { } } } }
From source file:com.cloud.test.longrun.User.java
public void launchUser() throws IOException { String encodedUsername = URLEncoder.encode(this.getUserName(), "UTF-8"); this.encryptedPassword = TestClientWithAPI.createMD5Password(this.getPassword()); String encodedPassword = URLEncoder.encode(this.encryptedPassword, "UTF-8"); String url = this.server + "?command=createUser&username=" + encodedUsername + "&password=" + encodedPassword + "&firstname=Test&lastname=Test&email=alena@vmops.com&domainId=1"; String userIdStr = null;// w w w . j a v a2s.c om HttpClient client = new HttpClient(); HttpMethod method = new GetMethod(url); int responseCode = client.executeMethod(method); if (responseCode == 200) { InputStream is = method.getResponseBodyAsStream(); Map<String, String> userIdValues = TestClientWithAPI.getSingleValueFromXML(is, new String[] { "id" }); userIdStr = userIdValues.get("id"); if ((userIdStr != null) && (Long.parseLong(userIdStr) != -1)) { this.setUserId(userIdStr); } } }
From source file:com.cloud.test.longrun.User.java
public void registerUser() throws HttpException, IOException { String encodedUsername = URLEncoder.encode(this.userName, "UTF-8"); String encodedPassword = URLEncoder.encode(this.password, "UTF-8"); String url = server + "?command=register&username=" + encodedUsername + "&domainid=1"; s_logger.info("registering: " + this.userName + " with url " + url); HttpClient client = new HttpClient(); HttpMethod method = new GetMethod(url); int responseCode = client.executeMethod(method); if (responseCode == 200) { InputStream is = method.getResponseBodyAsStream(); Map<String, String> requestKeyValues = TestClientWithAPI.getSingleValueFromXML(is, new String[] { "apikey", "secretkey" }); this.setApiKey(requestKeyValues.get("apikey")); this.setSecretKey(requestKeyValues.get("secretkey")); } else if (responseCode == 500) { InputStream is = method.getResponseBodyAsStream(); Map<String, String> errorInfo = TestClientWithAPI.getSingleValueFromXML(is, new String[] { "errorcode", "description" }); s_logger.error("registration failed with errorCode: " + errorInfo.get("errorCode") + " and description: " + errorInfo.get("description")); } else {/*from ww w . j av a 2 s. c o m*/ s_logger.error("internal error processing request: " + method.getStatusText()); } }
From source file:com.cloud.test.longrun.User.java
public void retrievePublicIp(long zoneId) throws IOException { String encodedApiKey = URLEncoder.encode(this.apiKey, "UTF-8"); String encodedZoneId = URLEncoder.encode("" + zoneId, "UTF-8"); String requestToSign = "apiKey=" + encodedApiKey + "&command=associateIpAddress" + "&zoneId=" + encodedZoneId;//w w w .j a v a 2s . c o m requestToSign = requestToSign.toLowerCase(); String signature = TestClientWithAPI.signRequest(requestToSign, this.secretKey); String encodedSignature = URLEncoder.encode(signature, "UTF-8"); String url = this.developerServer + "?command=associateIpAddress" + "&apiKey=" + encodedApiKey + "&zoneId=" + encodedZoneId + "&signature=" + encodedSignature; HttpClient client = new HttpClient(); HttpMethod method = new GetMethod(url); int responseCode = client.executeMethod(method); if (responseCode == 200) { InputStream is = method.getResponseBodyAsStream(); Map<String, String> values = TestClientWithAPI.getSingleValueFromXML(is, new String[] { "ipaddress" }); this.getPublicIp().add(values.get("ipaddress")); s_logger.info("Ip address is " + values.get("ipaddress")); } else if (responseCode == 500) { InputStream is = method.getResponseBodyAsStream(); Map<String, String> errorInfo = TestClientWithAPI.getSingleValueFromXML(is, new String[] { "errorcode", "description" }); s_logger.error("associate ip test failed with errorCode: " + errorInfo.get("errorCode") + " and description: " + errorInfo.get("description")); } else { s_logger.error("internal error processing request: " + method.getStatusText()); } }
From source file:com.knowledgebooks.rdf.SparqlClient.java
public SparqlClient(String endpoint_URL, String sparql) throws Exception { //System.out.println("SparqlClient("+endpoint_URL+", "+sparql+")"); HttpClient client = new HttpClient(); client.getHttpConnectionManager().getParams().setConnectionTimeout(10000); String req = URLEncoder.encode(sparql, "utf-8"); HttpMethod method = new GetMethod(endpoint_URL + "?query=" + req); method.setFollowRedirects(false);// www .j ava 2 s . c o m try { client.executeMethod(method); //System.out.println(method.getResponseBodyAsString()); //if (true) return; InputStream ins = method.getResponseBodyAsStream(); SAXParserFactory factory = SAXParserFactory.newInstance(); SAXParser sax = factory.newSAXParser(); sax.parse(ins, this); } catch (HttpException he) { System.err.println("Http error connecting to '" + endpoint_URL + "'"); } catch (IOException ioe) { System.err.println("Unable to connect to '" + endpoint_URL + "'"); } method.releaseConnection(); }
From source file:com.apifest.BasicTest.java
public String readResponse(HttpMethod method) throws IOException { HttpClient client = new HttpClient(); String response = null;//from w w w . j a v a 2 s . co m InputStream in = null; try { int status = client.executeMethod(method); if (status >= HttpStatus.SC_OK) { in = method.getResponseBodyAsStream(); response = readInputStream(in); } } catch (HttpException e) { log.error("cannot read response", e); } catch (IOException e) { log.error("cannot read response", e); } finally { in.close(); method.releaseConnection(); } return response; }
From source file:com.thoughtworks.go.agent.launcher.ServerCall.java
public static ServerResponseWrapper invoke(HttpMethod method) throws Exception { HashMap<String, String> headers = new HashMap<String, String>(); HttpClient httpClient = new HttpClient(); httpClient.setConnectionTimeout(HTTP_TIMEOUT_IN_MILLISECONDS); try {/* www. ja v a2 s.c o m*/ final int status = httpClient.executeMethod(method); if (status == HttpStatus.SC_NOT_FOUND) { StringWriter sw = new StringWriter(); PrintWriter out = new PrintWriter(sw); out.println("Return Code: " + status); out.println("Few Possible Causes: "); out.println("1. Your Go Server is down or not accessible."); out.println( "2. This agent might be incompatible with your Go Server.Please fix the version mismatch between Go Server and Go Agent."); out.close(); throw new Exception(sw.toString()); } if (status != HttpStatus.SC_OK) { throw new Exception("Got status " + status + " " + method.getStatusText() + " from server"); } for (Header header : method.getResponseHeaders()) { headers.put(header.getName(), header.getValue()); } return new ServerResponseWrapper(headers, method.getResponseBodyAsStream()); } catch (Exception e) { String message = "Couldn't access Go Server with base url: " + method.getURI() + ": " + e.toString(); LOG.error(message); throw new Exception(message, e); } finally { method.releaseConnection(); } }
From source file:com.ikon.util.MailUtils.java
/** * User tinyurl service as url shorter Depends on commons-httpclient:commons-httpclient:jar:3.0 because of * org.apache.jackrabbit:jackrabbit-webdav:jar:1.6.4 *///from ww w . j a v a 2s .co m public static String getTinyUrl(String fullUrl) throws HttpException, IOException { HttpClient httpclient = new HttpClient(); // Prepare a request object HttpMethod method = new GetMethod("http://tinyurl.com/api-create.php"); method.setQueryString(new NameValuePair[] { new NameValuePair("url", fullUrl) }); httpclient.executeMethod(method); InputStreamReader isr = new InputStreamReader(method.getResponseBodyAsStream(), "UTF-8"); StringWriter sw = new StringWriter(); int c; while ((c = isr.read()) != -1) sw.write(c); isr.close(); method.releaseConnection(); return sw.toString(); }
From source file:com.intellij.plugins.firstspirit.languagesupport.FirstSpiritClassPathHack.java
public void addFirstSpiritClientJar(UrlClassLoader classLoader, HttpScheme schema, String serverName, int port, String firstSpiritUserName, String firstSpiritUserPassword) throws Exception { System.out.println("starting to download fs-client.jar"); String resolvalbleAddress = null; // asking DNS for IP Address, if some error occur choose the given value from user try {// w w w.j a v a2 s . c o m InetAddress address = InetAddress.getByName(serverName); resolvalbleAddress = address.getHostAddress(); System.out.println("Resolved address: " + resolvalbleAddress); } catch (Exception e) { System.err.println("DNS cannot resolve address, using your given value: " + serverName); resolvalbleAddress = serverName; } String uri = schema + "://" + resolvalbleAddress + ":" + port + "/clientjar/fs-client.jar"; String versionUri = schema + "://" + resolvalbleAddress + ":" + port + "/version.txt"; String tempDirectory = System.getProperty("java.io.tmpdir"); System.out.println(uri); System.out.println(versionUri); HttpClient client = new HttpClient(); HttpMethod getVersion = new GetMethod(versionUri); client.executeMethod(getVersion); String currentServerVersionString = getVersion.getResponseBodyAsString(); System.out .println("FirstSpirit server you want to connect to is at version: " + currentServerVersionString); File fsClientJar = new File(tempDirectory, "fs-client-" + currentServerVersionString + ".jar"); if (!fsClientJar.exists()) { // get an authentication cookie from FirstSpirit HttpMethod post = new PostMethod(uri); post.setQueryString("login.user=" + URLEncoder.encode(firstSpiritUserName, "UTF-8") + "&login.password=" + URLEncoder.encode(firstSpiritUserPassword, "UTF-8") + "&login=webnonsso"); client.executeMethod(post); String setCookieJsession = post.getResponseHeader("Set-Cookie").getValue(); // download the fs-client.jar by using the authentication cookie HttpMethod get = new GetMethod(uri); get.getParams().setCookiePolicy(CookiePolicy.IGNORE_COOKIES); get.setRequestHeader("Cookie", setCookieJsession); client.executeMethod(get); InputStream inputStream = get.getResponseBodyAsStream(); FileOutputStream outputStream = new FileOutputStream(fsClientJar); outputStream.write(IOUtils.readFully(inputStream, -1, false)); outputStream.close(); System.out.println("tempfile of fs-client.jar created within path: " + fsClientJar); } addFile(classLoader, fsClientJar); }
From source file:com.bonitasoft.connector.Trello_Get_BoardImpl.java
/** * Method to get the specific Trello JSONArray from a http request. * @param method The httpMethod with the response * @return Specific Trello JSONArray/*from w w w .j a v a 2 s . c om*/ * @throws Exception */ private JSONArray getJSONFromResponse(HttpMethod method) throws Exception { BufferedReader reader = new BufferedReader(new InputStreamReader(method.getResponseBodyAsStream())); StringBuilder builder = new StringBuilder(); for (String line = null; (line = reader.readLine()) != null;) { builder.append(line).append("\n"); } JSONTokener tokener = new JSONTokener(builder.toString()); JSONObject tObject = null; JSONArray tArray = null; try { tObject = new JSONObject(tokener); tArray = new JSONArray(); tArray.put(tObject); } catch (JSONException e) { tokener = new JSONTokener(builder.toString()); tArray = new JSONArray(tokener); } return tArray; }