public boolean shutdown(int port, boolean ssl) { try { String protocol = "http" + (ssl ? "s" : ""); URL url = new URL(protocol, "127.0.0.1", port, "shutdown"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setRequestProperty("servicemanager", "shutdown"); conn.connect(); StringBuffer sb = new StringBuffer(); BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8")); int n; char[] cbuf = new char[1024]; while ((n = br.read(cbuf, 0, cbuf.length)) != -1) sb.append(cbuf, 0, n); br.close(); String message = sb.toString().replace("<br>", "\n"); if (message.contains("Goodbye")) { cp.appendln("Shutting down the server:"); String[] lines = message.split("\n"); for (String line : lines) { cp.append("..."); cp.appendln(line); } return true; } } catch (Exception ex) { } cp.appendln("Unable to shutdown CTP"); return false; }
private boolean handshake() throws Exception { URL homePage = new URL("http://mangaonweb.com/viewer.do?ctsn=" + ctsn); HttpURLConnection urlConn = (HttpURLConnection) homePage.openConnection(); urlConn.connect(); if (urlConn.getResponseCode() == HttpURLConnection.HTTP_NOT_FOUND) return (false); // save the cookie String headerName = null; for (int i = 1; (headerName = urlConn.getHeaderFieldKey(i)) != null; i++) { if (headerName.equals("Set-Cookie")) { cookies = urlConn.getHeaderField(i); } } // save cdn and crcod String page = "", line; BufferedReader stream = new BufferedReader(new InputStreamReader(urlConn.getInputStream(), "UTF-8")); while ((line = stream.readLine()) != null) page += line; cdn = param(page, "cdn"); crcod = param(page, "crcod"); return (true); }
public SetIfModifiedSince() throws Exception { serverSock = new ServerSocket(0); int port = serverSock.getLocalPort(); Thread thr = new Thread(this); thr.start(); Date date = new Date(new Date().getTime() - 1440000); // this time yesterday URL url; HttpURLConnection con; // url = new URL(args[0]); url = new URL("http://localhost:" + String.valueOf(port) + "/anything"); con = (HttpURLConnection) url.openConnection(); con.setIfModifiedSince(date.getTime()); con.connect(); int ret = con.getResponseCode(); if (ret == 304) { System.out.println("Success!"); } else { throw new RuntimeException( "Test failed! Http return code using setIfModified method is:" + ret + "\nNOTE:some web servers are not implemented according to RFC, thus a failed test does not necessarily indicate a bug in setIfModifiedSince method"); } }
Response(HttpURLConnection connection) throws IOException { try { connection.connect(); code = connection.getResponseCode(); headers = parseHeaders(connection); stream = isSuccessful() ? connection.getInputStream() : connection.getErrorStream(); } catch (UnknownHostException e) { throw new OAuthException("The IP address of a host could not be determined.", e); } }
public static boolean hasUpdate(int projectID, String version) { try { HttpURLConnection con = (HttpURLConnection) (new URL("https://api.curseforge.com/servermods/files?projectIds=" + projectID)) .openConnection(); con.setRequestMethod("GET"); con.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; JVM)"); con.setRequestProperty("Pragma", "no-cache"); con.connect(); JSONArray json = (JSONArray) JSONValue.parse(new InputStreamReader(con.getInputStream())); String[] cdigits = ((String) ((JSONObject) json.get(json.size() - 1)).get("name")) .toLowerCase() .split("\\."); String[] vdigits = version.toLowerCase().split("\\."); int max = vdigits.length > cdigits.length ? cdigits.length : vdigits.length; int a; int b; for (int i = 0; i < max; i++) { a = b = 0; try { a = Integer.parseInt(cdigits[i]); } catch (Throwable t1) { char[] c = cdigits[i].toCharArray(); for (int j = 0; j < c.length; j++) { a += (c[j] << ((c.length - (j + 1)) * 8)); } } try { b = Integer.parseInt(vdigits[i]); } catch (Throwable t1) { char[] c = vdigits[i].toCharArray(); for (int j = 0; j < c.length; j++) { b += (c[j] << ((c.length - (j + 1)) * 8)); } } if (a > b) { return true; } else if (a < b) { return false; } else if ((i == max - 1) && (cdigits.length > vdigits.length)) { return true; } } } catch (Throwable t) { } return false; }
private Map executeHTTP(Map data_to_send, boolean v6) throws Exception { if (v6 && !enable_v6) { throw (new Exception("IPv6 is disabled")); } String host = getHost(v6, HTTP_SERVER_ADDRESS_V6, HTTP_SERVER_ADDRESS_V4); if (Logger.isEnabled()) Logger.log( new LogEvent( LOGID, "VersionCheckClient retrieving " + "version information from " + host + ":" + HTTP_SERVER_PORT + " via HTTP")); String url_str = "http://" + (v6 ? UrlUtils.convertIPV6Host(host) : host) + (HTTP_SERVER_PORT == 80 ? "" : (":" + HTTP_SERVER_PORT)) + "/version?"; url_str += URLEncoder.encode(new String(BEncoder.encode(data_to_send), "ISO-8859-1"), "ISO-8859-1"); URL url = new URL(url_str); HttpURLConnection url_connection = (HttpURLConnection) url.openConnection(); url_connection.connect(); try { InputStream is = url_connection.getInputStream(); Map reply = BDecoder.decode(new BufferedInputStream(is)); preProcessReply(reply, v6); return (reply); } finally { url_connection.disconnect(); } }
private boolean checkServer(int port, boolean ssl) { try { URL url = new URL("http://127.0.0.1:" + port); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.connect(); int length = conn.getContentLength(); StringBuffer text = new StringBuffer(); InputStream is = conn.getInputStream(); InputStreamReader isr = new InputStreamReader(is); int size = 256; char[] buf = new char[size]; int len; while ((len = isr.read(buf, 0, size)) != -1) text.append(buf, 0, len); isr.close(); if (programName.equals("ISN")) return !shutdown(port, ssl); return true; } catch (Exception ex) { return false; } }
/** * 发起查询处理结果请求 * * @param params 请求参数 * @return 请求结果 * @throws IOException */ public Result getResult(Map<String, Object> params) throws IOException { InputStream is = null; HttpURLConnection conn; StringBuilder sb = new StringBuilder(HOST + "result"); sb.append("?"); for (Map.Entry<String, Object> mapping : params.entrySet()) { sb.append(mapping.getKey() + "=" + mapping.getValue().toString() + "&"); } URL url = new URL(sb.toString().substring(0, sb.length() - 1)); conn = (HttpURLConnection) url.openConnection(); // 设置必要参数 conn.setConnectTimeout(timeout); conn.setRequestMethod("GET"); conn.setUseCaches(false); conn.setDoOutput(true); conn.setRequestProperty("Connection", "Keep-Alive"); conn.setRequestProperty("User-Agent", UpYunUtils.VERSION); // 设置时间 conn.setRequestProperty(DATE, getGMTDate()); // 设置签名 conn.setRequestProperty(AUTHORIZATION, sign(params)); // 创建链接 conn.connect(); // 获取返回的信息 Result result = getResp(conn); if (is != null) { is.close(); } if (conn != null) { conn.disconnect(); } return result; }
@Test(groups = {"pulse"}) // test method public void testUserTx() throws Exception { try { String testurl = "http://" + host + ":" + port + "/" + strContextRoot + "/MyServlet?testcase=usertx"; URL url = new URL(testurl); echo("Connecting to: " + url.toString()); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.connect(); int responseCode = conn.getResponseCode(); InputStream is = conn.getInputStream(); BufferedReader input = new BufferedReader(new InputStreamReader(is)); String line = null; boolean result = false; String testLine = null; String EXPECTED_RESPONSE = "user-tx-commit:true"; String EXPECTED_RESPONSE2 = "user-tx-rollback:true"; while ((line = input.readLine()) != null) { // echo(line); if (line.indexOf(EXPECTED_RESPONSE) != -1 && line.indexOf(EXPECTED_RESPONSE2) != -1) { testLine = line; echo(testLine); result = true; break; } } Assert.assertEquals(result, true, "Unexpected Results"); } catch (Exception e) { e.printStackTrace(); throw new Exception(e); } }
protected Boolean doInBackground(ArrayList... params) { download_photos.this.runOnUiThread( new Runnable() { public void run() { mtext.setText( getText(R.string.download_textview_message_1) + " " + path.toString() + ". "); } }); if (resume_file.exists()) { initial_value = readProgress()[0]; } else { initial_value = 1; } for (int i = initial_value - 1; i < links.size(); i++) { // asynctask expects more than one ArrayList<String> item, but we are sending only one, // which is params[0] Uri imageuri = Uri.parse(params[0].get(i).toString()); URL imageurl = null; HttpURLConnection connection = null; total_files_to_download = links.size(); completed_downloads = i + 1; try { imageurl = new URL(params[0].get(i).toString()); connection = (HttpURLConnection) imageurl.openConnection(); connection.connect(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } // extracts the real file name of the photo from url path_segments = imageuri.getPathSegments(); int total_segments = path_segments.size(); file_name = path_segments.get(total_segments - 1); path.mkdirs(); // if(i==0) // first_image = path.toString() + "/" + file_name; InputStream input; OutputStream output; try { input = new BufferedInputStream(imageurl.openStream()); fully_qualified_file_name = new File(path, file_name); output = new BufferedOutputStream(new FileOutputStream(fully_qualified_file_name)); byte data[] = new byte[1024]; int count; while ((count = input.read(data)) != -1) { output.write(data, 0, count); } output.flush(); output.close(); input.close(); connection.disconnect(); new folder_scanner(getApplicationContext(), fully_qualified_file_name); publishProgress(completed_downloads, total_files_to_download); if (this.isCancelled()) { writeProgress(completed_downloads, total_files_to_download); break; } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } // creates required folders and subfolders if they do not exist already // boolean success = path.mkdirs(); // makes request to download photos // DownloadManager.Request request = new DownloadManager.Request(imageuri); // set path for downloads // request.setDestinationInExternalPublicDir(Environment.DIRECTORY_PICTURES,sub_path); // request.setDescription("Downloaded using Facebook Album Downloader"); // DownloadManager dm = (DownloadManager)getSystemService(DOWNLOAD_SERVICE); // download is enqueue in download list. it returns unique id for each download // download_id = dm.enqueue(request); } // returns the unique id. we are not using this id return true; }