public static void main(String[] args) { HttpClient client = new HttpClient(); // Create an instance of HttpClient. GetMethod method = new GetMethod(url); // Create a method instance. method .getParams() .setParameter( HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler( 3, false)); // Provide custom retry handler is necessary try { int statusCode = client.executeMethod(method); // Execute the method. if (statusCode != HttpStatus.SC_OK) { System.err.println("Method failed: " + method.getStatusLine()); } byte[] responseBody = method.getResponseBody(); // Read the response body. System.out.println( new String( responseBody)); // Deal with the response.// Use caution: ensure correct character // encoding and is not binary data } catch (HttpException e) { System.err.println("Fatal protocol violation: " + e.getMessage()); e.printStackTrace(); } catch (IOException e) { System.err.println("Fatal transport error: " + e.getMessage()); e.printStackTrace(); } finally { method.releaseConnection(); // Release the connection. } }
/** use httpclient to get the data */ public static ByteBuffer getDataFromURI(String uri) throws IOException { GetMethod get = new GetMethod(uri); try { new HttpClient().executeMethod(get); return new ByteBuffer(get.getResponseBodyAsStream()); } finally { get.releaseConnection(); } }
public boolean isApacheHttpd() throws Exception { GetMethod gm = new GetMethod(URL); try { httpResponseCode = httpClient.executeMethod(gm); } catch (HttpException e) { System.out.println("error: " + e); throw (e); } gm.releaseConnection(); Header head = gm.getResponseHeader("Server"); if (head != null) return head.toString().contains("Apache/2"); return false; }
/** * Run the first test. * * @param string a part of URL to connect to. * @return ManagerClient object * @throws IOException for any failures. */ public ManagerClient(String string) throws Exception { URL = "http://" + string + "/mod_cluster_manager/"; GetMethod gm = null; HttpMethodBase bm = null; if (httpClient == null) { httpClient = new HttpClient(); gm = new GetMethod(URL); bm = gm; } System.out.println("Connecting to " + URL); Integer connectionTimeout = 40000; bm.getParams().setParameter("http.socket.timeout", connectionTimeout); bm.getParams().setParameter("http.connection.timeout", connectionTimeout); httpClient.getParams().setParameter("http.socket.timeout", connectionTimeout); httpClient.getParams().setParameter("http.connection.timeout", connectionTimeout); try { httpResponseCode = httpClient.executeMethod(gm); if (httpResponseCode == 200) { // Read the nonce. String result = gm.getResponseBodyAsString(); String[] records = result.split("\n"); for (int i = 0; i < records.length; i++) { int j = records[i].indexOf("?nonce="); if (j < 0) continue; j = j + 7; String nnonce = records[i].substring(j); int k = nnonce.indexOf('&'); if (k > 0) { nonce = nnonce.substring(0, k); break; } } } else { System.out.println("response: " + httpResponseCode); System.out.println("response: " + bm.getStatusLine()); throw (new Exception("Reponse notok")); } // System.out.println("response:\n" + bm.getResponseBodyAsString(len)); } catch (HttpException e) { System.out.println("error: " + e); throw (e); } bm.releaseConnection(); }
/** * Obtem a timeline publica. Nao necessita de autenticacao, basicamente é um GET na URL * http://twitter.com/statuses/public_timeline.xml */ public String getPublicTimeline() throws Exception { HttpClient client = new HttpClient(); // get para obter a timeline publica GetMethod get = new GetMethod("/statuses/public_timeline.xml"); // Criando o host, para onde sera enviada a requisicao HostConfiguration host = client.getHostConfiguration(); host.setHost(new URI("http://twitter.com")); // executando o get na url de timeline publica do twitter client.executeMethod(host, get); // obtendo a resposta return get.getResponseBodyAsString(); }
private String DoCmd(String DURL) throws Exception { GetMethod gm = new GetMethod(DURL); try { httpResponseCode = httpClient.executeMethod(gm); if (httpResponseCode == 200) { String result = gm.getResponseBodyAsString(); gm.releaseConnection(); return result; } } catch (HttpException e) { System.out.println("error: " + e); throw (e); } gm.releaseConnection(); throw (new Exception("Reponse notok")); }
/** 根据模版及参数产生静态页面 */ public boolean createHtmlPage(String url, String htmlFileName) { boolean status = false; int statusCode = 0; try { // 创建一个HttpClient实例充当模拟浏览器 httpClient = new HttpClient(); // 设置httpclient读取内容时使用的字符集 httpClient.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "gbk"); // 创建GET方法的实例 getMethod = new GetMethod(url); // 使用系统提供的默认的恢复策略,在发生异常时候将自动重试3次 getMethod .getParams() .setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler()); // 设置Get方法提交参数时使用的字符集,以支持中文参数的正常传递 getMethod.addRequestHeader("Content-Type", "text/html;charset=gbk"); // 执行Get方法并取得返回状态码,200表示正常,其它代码为异常 statusCode = httpClient.executeMethod(getMethod); if (statusCode != 200) { logger.fatal("静态页面引擎在解析" + url + "产生静态页面" + htmlFileName + "时出错!"); } else { // 读取解析结果 sb = new StringBuffer(); in = getMethod.getResponseBodyAsStream(); br = new BufferedReader(new InputStreamReader(in)); while ((line = br.readLine()) != null) { sb.append(line + "\n"); } if (br != null) br.close(); page = sb.toString(); // 将页面中的相对路径替换成绝对路径,以确保页面资源正常访问 page = formatPage(page); // 将解析结果写入指定的静态HTML文件中,实现静态HTML生成 writeHtml(htmlFileName, page); status = true; } } catch (Exception ex) { logger.fatal("静态页面引擎在解析" + url + "产生静态页面" + htmlFileName + "时出错:" + ex.getMessage()); } finally { // 释放http连接 getMethod.releaseConnection(); } return status; }
// ���� URL ָ�����ҳ public String downloadFile(String url) { String filePath = null; // 1.���� HttpClinet�������ò��� HttpClient httpClient = new HttpClient(); // ���� HTTP���ӳ�ʱ 5s httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(5000); // 2.���� GetMethod�������ò��� GetMethod getMethod = new GetMethod(url); // ���� get����ʱ 5s getMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 5000); // �����������Դ��� getMethod .getParams() .setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler()); // 3.ִ��GET���� try { int statusCode = httpClient.executeMethod(getMethod); // �жϷ��ʵ�״̬�� if (statusCode != HttpStatus.SC_OK) { System.err.println("Method failed: " + getMethod.getStatusLine()); filePath = null; } // 4.���� HTTP ��Ӧ���� byte[] responseBody = getMethod.getResponseBody(); // ��ȡΪ�ֽ����� // ������ҳ url ���ɱ���ʱ���ļ��� filePath = "temp\\" + getFileNameByUrl(url, getMethod.getResponseHeader("Content-Type").getValue()); File file = new File(filePath); if (!file.getParentFile().exists()) { file.getParentFile().mkdir(); } saveToLocal(responseBody, filePath); } catch (HttpException e) { // �����������쳣��������Э�鲻�Ի��߷��ص����������� System.out.println("�������http��ַ�Ƿ���ȷ"); e.printStackTrace(); } catch (IOException e) { // ���������쳣 e.printStackTrace(); } finally { // �ͷ����� getMethod.releaseConnection(); } return filePath; }
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { address = PAConfiguration.getAddress(); port = PAConfiguration.getPort(instantiation); poslAddress = PAConfiguration.getPOSL(instantiation, topic); rdfAddress = PAConfiguration.getRDFTaxonomy(instantiation); messageEndpoint = PAConfiguration.getEndpointName(instantiation, topic); } catch (BadConfigurationException e) { System.out.println(e.getMessage()); e.printStackTrace(); System.exit(0); } response.setContentType("text/html; charset=UTF-8"); PrintWriter out = response.getWriter(); try { System.out.println("5 Publicty Chair Servlet"); System.out.println(response.toString()); BufferedReader brd = request.getReader(); String input = ""; String message = ""; while (!input.equals("</RuleML>")) { input = brd.readLine(); message = message + input; } String[] varOrder = getVariableOrder(message); System.out.println("Received Message: " + message); // BackwardReasoner br = new BackwardReasoner(); // Iterator solit =null; // DefiniteClause dc = null; // SymbolTable.reset(); POSLParser pp = new POSLParser(); // String contents = "c(a).\nc(b).\nc(c)."; Date t1 = new GregorianCalendar().getTime(); System.out.println(t1.getHours() + ":" + t1.getMinutes()); // append time to contents System.out.println("day: " + t1.getDay()); System.out.println("day: " + t1.getYear()); System.out.println("day: " + t1.getMonth()); // time String time = "time(" + t1.getHours() + ":integer)."; System.out.println(time); String url = poslAddress; // String url = "http://www.jdrew.org/oojdrew/test.posl"; String contents = ""; // day of the week int day = t1.getDay(); boolean weekday = true; if (day == 0 || day == 6) { weekday = false; } String dayOfWeek; if (weekday) { dayOfWeek = "day(weekday)."; } else { dayOfWeek = "day(weekend)."; } // full date Calendar cal = new GregorianCalendar(); int year = cal.get(Calendar.YEAR); int month = cal.get(Calendar.MONTH) + 1; int day2 = cal.get(Calendar.DAY_OF_MONTH); String date; String day3 = "" + day2; if (day2 == 1 || day2 == 2 || day2 == 3 || day2 == 4 || day2 == 5 || day2 == 6 || day2 == 7 || day2 == 8 || day2 == 9) { day3 = "0" + day2; } if (month == 10 || month == 11 || month == 12) date = "" + year + month + day3; else date = "" + year + "0" + month + day3; date = "date(" + date + ":integer)."; System.out.println(date); String url2 = rdfAddress; HttpClient client2 = new HttpClient(); GetMethod method2 = new GetMethod(url2); method2.setFollowRedirects(true); String typestr = ""; // Execute the GET method int statusCode2 = client2.executeMethod(method2); if (statusCode2 != -1) { typestr = method2.getResponseBodyAsString(); } System.out.println("Types: " + typestr); Types.reset(); RDFSParser.parseRDFSString(typestr); try { HttpClient client = new HttpClient(); GetMethod method = new GetMethod(url); method.setFollowRedirects(true); // Execute the GET method int statusCode = client.executeMethod(method); if (statusCode != -1) { contents = method.getResponseBodyAsString(); } } catch (Exception e) { e.printStackTrace(); } contents = contents + "\n" + time; contents = contents + "\n" + dayOfWeek; contents = contents + "\n" + date; BackwardReasoner br = new BackwardReasoner(); Iterator solit = null; DefiniteClause dc = null; SymbolTable.reset(); pp.parseDefiniteClauses(contents); br.loadClauses(pp.iterator()); System.out.println("TEST"); Iterator it = pp.iterator(); while (it.hasNext()) { DefiniteClause d = (DefiniteClause) it.next(); System.out.println("Loaded clause: " + d.toPOSLString()); } br = new BackwardReasoner(br.clauses, br.oids); MessageParser m = new MessageParser(message); Element atom = null; try { atom = m.parseForContent(); } catch (Exception e) { System.out.println("Invalid Message"); // out.flush(); } QueryBuilder q = new QueryBuilder(atom); String query = q.generateDoc(); System.out.println("ABOUT TO INPUT THIS QUERY:" + query); RuleMLParser qp = new RuleMLParser(); try { dc = qp.parseRuleMLQuery(query); } catch (Exception e) { System.out.println("Invalid Query"); // out.flush(); } // solit = br.iterativeDepthFirstSolutionIterator(dc); solit = br.iterativeDepthFirstSolutionIterator(dc); int varSize = 0; while (solit.hasNext()) { Vector data = new Vector(); BackwardReasoner.GoalList gl = (BackwardReasoner.GoalList) solit.next(); Hashtable varbind = gl.varBindings; javax.swing.tree.DefaultMutableTreeNode root = br.toTree(); root.setAllowsChildren(true); javax.swing.tree.DefaultTreeModel dtm = new DefaultTreeModel(root); int i = 0; Object[][] rowdata = new Object[varbind.size()][2]; varSize = varbind.size(); Enumeration e = varbind.keys(); while (e.hasMoreElements()) { Object k = e.nextElement(); Object val = varbind.get(k); String ks = (String) k; rowdata[i][0] = ks; rowdata[i][1] = val; i++; } data.addElement(rowdata); String[] messages = new String[data.size()]; MessageGenerator g = new MessageGenerator( data, varSize, messageEndpoint, m.getId(), m.getProtocol(), m.getRel(), varOrder); messages = g.Messages2(); String appender = ""; URL sender = new URL(address + ":" + port); HttpMessage msg = new HttpMessage(sender); Properties props = new Properties(); for (int i1 = 0; i1 < data.size(); i1++) { System.out.println(i1 + ")" + messages[i1].toString()); props.put("text", messages[i1].toString()); InputStream in = msg.sendGetMessage(props); } System.out.println("NEXT MESSAGE"); } MessageGenerator g = new MessageGenerator( null, varSize, messageEndpoint, m.getId(), m.getProtocol(), m.getRel()); URL sender = new URL(address + ":" + port); HttpMessage msg = new HttpMessage(sender); Properties props = new Properties(); String finalMessage = g.finalMessage(query); System.out.println(finalMessage); props.put("text", finalMessage); InputStream in = msg.sendGetMessage(props); System.out.println("Stop_Communication"); } catch (Exception e) { System.out.println("ERROR has occured : " + e.toString()); } out.close(); }