List of usage examples for org.apache.commons.httpclient.methods GetMethod GetMethod
public GetMethod(String uri)
From source file:com.assemblade.client.AbstractClient.java
protected <T> T getFromUrl(String url, TypeReference<T> type) throws ClientException { GetMethod get = new GetMethod(url); try {//from w ww . j a v a 2 s .c om int statusCode = executeMethod(get); if (statusCode == 200) { try { return mapper.readValue(get.getResponseBodyAsStream(), type); } catch (IOException e) { throw new CallFailedException("Failed to deserialize a response object", e); } } else { throw new InvalidStatusException(200, statusCode); } } finally { get.releaseConnection(); } }
From source file:buildhappy.tools.DownloadFile.java
/** * URL/*from www . j a v a 2 s . co m*/ */ public String downloadFile(String url) { String filePath = null; //1.?HttpClient?? HttpClient client = new HttpClient(); //5s client.getHttpConnectionManager().getParams().setConnectionTimeout(5000); //2.?GetMethod? GetMethod getMethod = new GetMethod(url); //get5s getMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 5000); //?? getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler()); //3.http get try { int statusCode = client.executeMethod(getMethod); if (statusCode != HttpStatus.SC_OK) { System.err.println("Method failed:" + getMethod.getStatusLine()); filePath = null; } //4.?HTTP? InputStream in = getMethod.getResponseBodyAsStream(); BufferedInputStream buffIn = new BufferedInputStream(in); //byte[] responseBody = null; String responseBody = null; StringBuffer strBuff = new StringBuffer(); byte[] b = new byte[1024]; int readByte = 0; while ((readByte = buffIn.read(b)) != -1) { strBuff.append(new String(b)); } responseBody = strBuff.toString(); //buffIn.read(responseBody, off, len) //byte[] responseBody = getMethod.getResponseBody(); //?url???? filePath = "temp\\" + getFileNameByUrl(url, getMethod.getResponseHeader("Content-Type").getValue()); System.out.println(filePath + "--size:" + responseBody.length()); saveToLocal(responseBody.getBytes(), filePath); } catch (HttpException e) { System.out.println("check your http address"); e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { // getMethod.releaseConnection(); } return filePath; }
From source file:com.cloud.test.regression.Test.java
public boolean executeTest() { int error = 0; Element rootElement = this.getInputFile().get(0).getDocumentElement(); NodeList commandLst = rootElement.getElementsByTagName("command"); //Analyze each command, send request and build the array list of api commands for (int i = 0; i < commandLst.getLength(); i++) { Node fstNode = commandLst.item(i); Element fstElmnt = (Element) fstNode; //new command ApiCommand api = new ApiCommand(fstElmnt, this.getParam(), this.getCommands()); //send a command api.sendCommand(this.getClient(), null); }// ww w . j a va 2 s . c o m //Try to create portForwarding rule for all available private/public ports ArrayList<String> port = new ArrayList<String>(); for (int j = 1; j < 1000; j++) { port.add(Integer.toString(j)); } //try all public ports for (String portValue : port) { try { s_logger.info("public port is " + portValue); String url = "http://" + this.getParam().get("hostip") + ":8096/?command=createNetworkRule&publicPort=" + portValue + "&privatePort=22&protocol=tcp&isForward=true&securityGroupId=1&account=admin"; HttpClient client = new HttpClient(); HttpMethod method = new GetMethod(url); int responseCode = client.executeMethod(method); if (responseCode != 200) { error++; s_logger.error("Can't create portForwarding network rule for the public port " + portValue + ". Request was sent with url " + url); } } catch (Exception ex) { s_logger.error(ex); } } if (error != 0) return false; else return true; }
From source file:com.cloud.storage.template.MetalinkTemplateDownloader.java
protected GetMethod createRequest(String downloadUrl) { GetMethod request = new GetMethod(downloadUrl); request.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, myretryhandler); request.setFollowRedirects(true);/*from w w w .jav a 2s . co m*/ if (!toFileSet) { String[] parts = downloadUrl.split("/"); String filename = parts[parts.length - 1]; _toFile = _toDir + File.separator + filename; toFileSet = true; } return request; }
From source file:com.mythesis.userbehaviouranalysis.DBpediaSpotlightClient.java
@Override public List<DBpediaResource> extract(Text text) throws AnnotationException { LOG.info("Querying API."); String spotlightResponse;/*from w w w . j av a2 s.c o m*/ try { GetMethod getMethod = new GetMethod(API_URL + "rest/annotate/?" + "confidence=" + CONFIDENCE + "&support=" + SUPPORT + "&text=" + URLEncoder.encode(text.text(), "utf-8")); getMethod.addRequestHeader(new Header("Accept", "application/json")); spotlightResponse = request(getMethod); } catch (UnsupportedEncodingException e) { throw new AnnotationException("Could not encode text.", e); } assert spotlightResponse != null; JSONObject resultJSON = null; JSONArray entities = null; try { resultJSON = new JSONObject(spotlightResponse); entities = resultJSON.getJSONArray("Resources"); } catch (JSONException e) { throw new AnnotationException("Received invalid response from DBpedia Spotlight API."); } LinkedList<DBpediaResource> resources = new LinkedList<DBpediaResource>(); for (int i = 0; i < entities.length(); i++) { try { JSONObject entity = entities.getJSONObject(i); resources.add(new DBpediaResource(entity.getString("@URI"), Integer.parseInt(entity.getString("@support")))); } catch (JSONException e) { LOG.error("JSON exception " + e); } } return resources; }
From source file:com.eclectide.intellij.whatthecommit.WhatTheCommitAction.java
public String loadCommitMessage(final String url) { final FutureTask<String> downloadTask = new FutureTask<String>(new Callable<String>() { public String call() { final HttpClient client = new HttpClient(); final GetMethod getMethod = new GetMethod(url); try { final int statusCode = client.executeMethod(getMethod); if (statusCode != HttpStatus.SC_OK) throw new RuntimeException("Connection error (HTTP status = " + statusCode + ")"); return getMethod.getResponseBodyAsString(); } catch (IOException e) { throw new RuntimeException(e.getMessage(), e); }//from www . ja va 2s . c o m } }); ApplicationManager.getApplication().executeOnPooledThread(downloadTask); try { return downloadTask.get(TIMEOUT_SECONDS, TimeUnit.SECONDS); } catch (TimeoutException e) { // ignore } catch (Exception e) { throw new RuntimeException(e.getMessage(), e); } if (!downloadTask.isDone()) { downloadTask.cancel(true); throw new RuntimeException("Connection timed out"); } return ""; }
From source file:com.zimbra.cs.datasource.RssImport.java
public void test() throws ServiceException { Mailbox mbox = DataSourceManager.getInstance().getMailbox(mDataSource); int folderId = mDataSource.getFolderId(); Folder folder = mbox.getFolderById(null, folderId); String urlString = folder.getUrl(); if (StringUtil.isNullOrEmpty(urlString)) { throw ServiceException.FAILURE("URL not specified for folder " + folder.getPath(), null); }//w w w . ja va 2s. c o m GetMethod get = new GetMethod(urlString); try { HttpClient client = ZimbraHttpConnectionManager.getExternalHttpConnMgr().newHttpClient(); HttpProxyUtil.configureProxy(client); HttpClientUtil.executeMethod(client, get); get.getResponseContentLength(); } catch (Exception e) { throw ServiceException.FAILURE("Data source test failed.", e); } finally { get.releaseConnection(); } }
From source file:com.cerema.cloud2.lib.resources.users.GetRemoteUserNameOperation.java
@Override protected RemoteOperationResult run(OwnCloudClient client) { RemoteOperationResult result = null; int status = -1; GetMethod get = null;//from w ww. j ava2 s. c o m //Get the user try { get = new GetMethod(client.getBaseUri() + OCS_ROUTE); get.addRequestHeader(OCS_API_HEADER, OCS_API_HEADER_VALUE); status = client.executeMethod(get); if (isSuccess(status)) { String response = get.getResponseBodyAsString(); Log_OC.d(TAG, "Successful response: " + response); // Parse the response JSONObject respJSON = new JSONObject(response); JSONObject respOCS = respJSON.getJSONObject(NODE_OCS); JSONObject respData = respOCS.getJSONObject(NODE_DATA); String id = respData.getString(NODE_ID); String displayName = respData.getString(NODE_DISPLAY_NAME); String email = respData.getString(NODE_EMAIL); // Result result = new RemoteOperationResult(true, status, get.getResponseHeaders()); // Username in result.data ArrayList<Object> data = new ArrayList<Object>(); data.add(displayName); result.setData(data); mUserName = displayName; Log_OC.d(TAG, "*** Parsed user information: " + id + " - " + displayName + " - " + email); } else { result = new RemoteOperationResult(false, status, get.getResponseHeaders()); String response = get.getResponseBodyAsString(); Log_OC.e(TAG, "Failed response while getting user information "); if (response != null) { Log_OC.e(TAG, "*** status code: " + status + " ; response message: " + response); } else { Log_OC.e(TAG, "*** status code: " + status); } } } catch (Exception e) { result = new RemoteOperationResult(e); Log_OC.e(TAG, "Exception while getting OC user information", e); } finally { get.releaseConnection(); } return result; }
From source file:com.epam.wilma.gepard.testclient.HttpGetRequestSender.java
/** * Sends a new HTTP request to a server through a proxy. Also logs request and response with gepard framework. * * @param tc is the caller Test Case./*from w w w .j av a 2 s .co m*/ * @param requestParameters a set of parameters that will set the content of the request * and specify the proxy it should go through * @return with Response Holder class. * @throws IOException in case error occurs * @throws ParserConfigurationException in case error occurs * @throws SAXException in case error occurs */ public ResponseHolder callWilmaTestServer(final WilmaTestCase tc, final RequestParameters requestParameters) throws IOException, ParserConfigurationException, SAXException { String responseCode; ResponseHolder responseMessage; HttpClient httpClient = new HttpClient(); GetMethod httpGet = new GetMethod(requestParameters.getTestServerUrl()); if (requestParameters.isUseProxy()) { httpClient.getHostConfiguration().setProxy(requestParameters.getWilmaHost(), requestParameters.getWilmaPort()); } createRequest(requestParameters, httpGet); tc.logGetRequestEvent(requestParameters); //this dumps the request String sendBuffer; try { sendBuffer = tc.getTestClassExecutionData().getEnvironment().getProperty("http.socket.sendbuffer"); } catch (NullPointerException e) { sendBuffer = DEFAULT_BUFFER_SIZE_STRING; } String receiveBuffer; try { receiveBuffer = tc.getTestClassExecutionData().getEnvironment() .getProperty("http.socket.receivebuffer"); } catch (NullPointerException e) { receiveBuffer = DEFAULT_BUFFER_SIZE_STRING; } httpClient.getHttpConnectionManager().getParams().setSendBufferSize(Integer.valueOf(sendBuffer)); httpClient.getHttpConnectionManager().getParams().setReceiveBufferSize(Integer.valueOf(receiveBuffer)); int statusCode; statusCode = httpClient.executeMethod(httpGet); responseCode = "status code: " + statusCode + "\n"; responseMessage = createResponse(httpGet); responseMessage.setResponseCode(responseCode); tc.setActualResponseCode(statusCode); Header contentTypeHeader = httpGet.getResponseHeader("Content-Type"); if (contentTypeHeader != null) { tc.setActualResponseContentType(contentTypeHeader.getValue()); } Header sequenceHeader = httpGet.getResponseHeader("Wilma-Sequence"); if (sequenceHeader != null) { tc.setActualDialogDescriptor(sequenceHeader.getValue()); } tc.logResponseEvent(responseMessage); //this dumps the response return responseMessage; }
From source file:com.dragoniade.deviantart.deviation.SearchStream.java
public List<Deviation> search(ProgressDialog progress, Collection collection) { if (user == null) { throw new IllegalStateException("You must set the user before searching."); }/*from www .j a va 2 s. com*/ if (search == null) { throw new IllegalStateException("You must set the search type before searching."); } String searchQuery = search.getSearch().replace("%username%", user); String queryString = "http://www.deviantart.com/global/difi.php?c=Stream;thumbs;" + searchQuery + "," + offset + "," + OFFSET + "&t=xml"; GetMethod method = new GetMethod(queryString); List<Deviation> results = new ArrayList<Deviation>(OFFSET); try { int sc = -1; do { sc = client.executeMethod(method); if (sc != 200) { int res = DialogHelper.showConfirmDialog(owner, "An error has occured when contacting deviantART : error " + sc + ". Try again?", "Continue?", JOptionPane.YES_NO_OPTION); if (res == JOptionPane.NO_OPTION) { return null; } try { Thread.sleep(500); } catch (InterruptedException e) { } } } while (sc != 200); XmlToolkit toolkit = XmlToolkit.getInstance(); StringBuilder stringBuilder = new StringBuilder(); InputStream inputStream = method.getResponseBodyAsStream(); int b; boolean isOpening = false; while ((b = inputStream.read()) > -1) { if (b > 127) { isOpening = false; continue; } char c = (char) b; if (isOpening && Character.isDigit(c)) { stringBuilder.append('_'); } if (isOpening && c == '/') { stringBuilder.append(c); continue; } isOpening = (c == '<'); stringBuilder.append(c); } Element responses = toolkit.parseDocument(stringBuilder.toString()); method.releaseConnection(); total = toolkit.getNodeAsInt(responses, "response/calls/response/content/total"); List<?> deviations = toolkit.getMultipleNodes(responses, "response/calls/response/content/deviations"); if (total == 0) { return results; } for (Object obj : deviations) { Element deviation = (Element) obj; Deviation da = new Deviation(); da.setId(toolkit.getNodeAsLong(deviation, "id")); da.setArtist(toolkit.getNodeAsString(deviation, "artist")); da.setCategory(toolkit.getNodeAsString(deviation, "category")); da.setTitle(toolkit.getNodeAsString(deviation, "title")); da.setUrl(toolkit.getNodeAsString(deviation, "url")); da.setTimestamp(new Date(toolkit.getNodeAsLong(deviation, "ts") * 1000)); da.setMature("1".equals(toolkit.getNodeAsString(deviation, "is_mature"))); da.setCollection(collection); String filenameStr = toolkit.getNodeAsString(deviation, "filename"); String imageUrl = toolkit.getNodeAsString(deviation, "image/url"); String primaryFilename = Deviation.extractFilename(filenameStr); da.setDocumentDownloadUrl(DOWNLOAD_URL + da.getId() + "/"); da.setDocumentFilename(primaryFilename); if (imageUrl != null) { String secondaryFilename = Deviation.extractFilename(imageUrl); da.setImageDownloadUrl(imageUrl); da.setImageFilename(secondaryFilename); da.setResolution(toolkit.getNodeAsString(deviation, "image/width") + "x" + toolkit.getNodeAsString(deviation, "image/height")); } results.add(da); } offset = offset + deviations.size(); return results; } catch (HttpException e) { DialogHelper.showMessageDialog(owner, "Error contacting deviantART : " + e.getMessage() + ".", "Error", JOptionPane.ERROR_MESSAGE); return null; } catch (IOException e) { DialogHelper.showMessageDialog(owner, "Error contacting deviantART : " + e.getMessage() + ".", "Error", JOptionPane.ERROR_MESSAGE); return null; } }