下面列出了java.net.HttpURLConnection#getContent ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* Check if HTTP connection to URL is reachable
*
* @param checkURL
* @return boolean
*/
public static boolean isHTTPreachable(String checkURL) {
try {
// make a URL to a known source
URL url = new URL(checkURL);
// open a connection to that source
HttpURLConnection urlConnect = (HttpURLConnection) url.openConnection();
// trying to retrieve data from the source. If there
// is no connection, this line will fail
Object objData = urlConnect.getContent();
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
private void createInfluxdbRetentionPolicy(String host, String port, String username, String password,
String database, String retentionPeriod) {
try {
StringBuffer url = new StringBuffer();
url.append(HTTP).append(host.trim()).append(COLON).append(port).append("/query?u=").append(username)
.append(AND_P_EQUAL_TO).append(password).append(AND_Q_EQUAL_TO)
.append("CREATE%20RETENTION%20POLICY%20ret_" + database + "%20on%20" + database + "%20DURATION%20"
+ retentionPeriod + "d%20REPLICATION%201%20DEFAULT");
URL obj = new URL(url.toString());
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("GET");
con.setRequestProperty("User-Agent", "Mozilla/5.0");
con.getContent();
con.disconnect();
} catch (Exception e) {
}
}
private void updateRetentionPolicy(String host, String port, String username, String password,
String database, String retentionPeriod) {
try {
StringBuffer url = new StringBuffer();
url.append(HTTP).append(host.trim()).append(COLON).append(port).append("/query?u=").append(username)
.append(AND_P_EQUAL_TO).append(password).append(AND_Q_EQUAL_TO);
url.append("ALTER%20RETENTION%20POLICY%20ret_" + database + "%20on%20" + database + "%20DURATION%20"
+ retentionPeriod + "d");
URL obj = new URL(url.toString());
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("GET");
con.setRequestProperty("User-Agent", "Mozilla/5.0");
con.getContent();
con.disconnect();
} catch (Exception e) {
}
}
public void createInfluxdbDatabase(String host, String port, String username,
String password, String database) {
try {
StringBuffer url = new StringBuffer();
url.append(HTTP).append(host).append(COLON).append(port).append("/query?");
url.append("u=").append(username).append(AND_P_EQUAL_TO).append(password);
url.append(AND_Q_EQUAL_TO).append("create%20database%20" + database);
URL obj = new URL(url.toString());
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("GET");
con.setRequestProperty("User-Agent", "Mozilla/5.0");
con.getContent();
con.disconnect();
} catch (Exception e) {
}
}
/**
* Create database in influxdb according to configuration provided
*
* @param configuration
* @throws Exception
*/
public static void dropDatabase(InfluxDBConf configuration) throws Exception {
StringBuffer url = new StringBuffer();
url.append(HTTP).append(configuration.getHost().trim()).append(COLON)
.append(configuration.getPort()).append("/query?u=")
.append(configuration.getUsername()).append(AND_P_EQUAL_TO)
.append(configuration.getDecryptedPassword()).append(AND_Q_EQUAL_TO)
.append("drop%20database%20" + configuration.getDatabase());
URL obj = new URL(url.toString());
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod(GET);
con.setRequestProperty(USER_AGENT, MOZILLA_5_0);
con.getContent();
con.disconnect();
}
/**
* Create database in influxdb according to configuration provided
*
* @param configuration
* @throws Exception
*/
public static void createRetentionPolicy(InfluxDBConf configuration) {
try {
StringBuffer url = new StringBuffer();
url.append(HTTP).append(configuration.getHost().trim()).append(COLON)
.append(configuration.getPort()).append("/query?u=")
.append(configuration.getUsername()).append(AND_P_EQUAL_TO)
.append(configuration.getDecryptedPassword()).append(AND_Q_EQUAL_TO)
.append("CREATE%20RETENTION%20POLICY%20ret_" + configuration.getDatabase()
+ "%20on%20" + configuration
.getDatabase()
+ "%20DURATION%2090d%20REPLICATION%201%20DEFAULT");
URL obj = new URL(url.toString());
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod(GET);
con.setRequestProperty(USER_AGENT, MOZILLA_5_0);
con.getContent();
con.disconnect();
} catch (Exception e) {
LOGGER.error("Unable to create retention policy in influxdata for database + "
+ configuration.getDatabase());
}
}
public static void updateRetentionPolicy(InfluxDBConf configuration) {
try {
StringBuffer url = new StringBuffer();
url.append(HTTP).append(configuration.getHost().trim()).append(COLON)
.append(configuration.getPort()).append("/query?u=")
.append(configuration.getUsername()).append(AND_P_EQUAL_TO)
.append(configuration.getDecryptedPassword()).append(AND_Q_EQUAL_TO);
url.append("ALTER%20RETENTION%20POLICY%20ret_" + configuration.getDatabase()
+ "%20on%20" + configuration.getDatabase() + "%20DURATION%20"
+ configuration.getRetentionPeriod() + "d");
URL obj = new URL(url.toString());
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod(GET);
con.setRequestProperty(USER_AGENT, MOZILLA_5_0);
con.getContent();
con.disconnect();
} catch (Exception e) {
LOGGER.error("Unable to update retention policy in influxdata for database + "
+ configuration.getDatabase());
}
}
public static boolean isInternetReachable() {
try {
// make a URL to a known source
URL url = new URL(WSO2PluginConstants.GOOGLE_COM);
// open a connection to that source
HttpURLConnection urlConnect = (HttpURLConnection) url.openConnection();
// trying to retrieve data from the source. If there
// is no connection, this line will fail
Object objData = urlConnect.getContent();
} catch (IOException e) {
return false;
}
return true;
}
private static boolean IsReachable(String url) {
System.out.println("Testing connectivity to " + url);
try {
//make a URL to a known source
URL url2 = new URL(url);
//open a connection to that source
HttpURLConnection urlConnect = (HttpURLConnection) url2.openConnection();
//trying to retrieve data from the source. If there
//is no connection, this line will fail
Object objData = urlConnect.getContent();
urlConnect.disconnect();
} catch (Exception e) {
System.out.println("Connectivity failed " + e.getMessage());
return false;
}
System.out.println("Connectivity passed");
return true;
}
private static boolean IsReachable(String url) {
System.out.println("Testing connectivity to " + url);
try {
//make a URL to a known source
URL url2 = new URL(url);
//open a connection to that source
HttpURLConnection urlConnect = (HttpURLConnection) url2.openConnection();
//trying to retrieve data from the source. If there
//is no connection, this line will fail
Object objData = urlConnect.getContent();
urlConnect.disconnect();
} catch (Exception e) {
System.out.println("Connectivity failed " + e.getMessage());
return false;
}
System.out.println("Connectivity passed" );
return true;
}
private FeatureToggleResponse getToggleResponse(HttpURLConnection request) throws IOException {
etag = Optional.ofNullable(request.getHeaderField("ETag"));
try(BufferedReader reader = new BufferedReader(
new InputStreamReader((InputStream) request.getContent(), StandardCharsets.UTF_8))) {
ToggleCollection toggles = JsonToggleParser.fromJson(reader);
return new FeatureToggleResponse(FeatureToggleResponse.Status.CHANGED, toggles);
}
}
private Pair<String, Integer> get(String url, String token) throws IOException {
URL createUrl = new URL(url);
HttpURLConnection createConn = (HttpURLConnection) createUrl.openConnection();
if (token != null)
createConn.setRequestProperty("Authorization", "Bearer " + token);
BufferedReader br2 = new BufferedReader(new InputStreamReader((InputStream) createConn.getContent(), StandardCharsets.UTF_8));
String result = br2.lines().collect(Collectors.joining("\n"));
int code = createConn.getResponseCode();
createConn.disconnect();
return new Pair<>(result, code);
}
/**
* Determines if a url path is available (ie both valid and connected).
*
* @param urlPath the path in URI form
* @return true if available
*/
public static boolean isURLAvailable(String urlPath) {
try {
// make a URL, open a connection, get content
URL url = new URL(urlPath);
HttpURLConnection urlConnect = (HttpURLConnection)url.openConnection();
urlConnect.getContent();
} catch (Exception ex) {
return false;
}
return true;
}
private static void testReachable(URL url) throws IOException {
log.info("Trying to connect to {}", url.toString());
HttpURLConnection urlConnection = null;
try {
urlConnection = ((HttpURLConnection) url.openConnection());
urlConnection.getContent();
log.info("Client is able to connect to the selenium hub");
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
}
}
public int urlWithConnection(String urlString) throws IOException {
URL url = new URL(urlString);
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("GET");
connection.connect();
connection.getContent();
return connection.getResponseCode();
}
@Test
public void testFunc() throws Exception {
URL url = new URL("http://192.168.0.77/kupai");
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
OutputStream os = conn.getOutputStream();
os.write(post.getBytes());
os.close();
Object obj = conn.getContent();
int code = conn.getResponseCode();
System.out.println("code:"+code+", obj:"+obj);
fail("Not yet implemented");
}
@Test
public void testFunc() throws Exception {
URL url = new URL("http://192.168.0.77/kupai");
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
OutputStream os = conn.getOutputStream();
os.write(post.getBytes());
os.close();
Object obj = conn.getContent();
int code = conn.getResponseCode();
System.out.println("code:"+code+", obj:"+obj);
fail("Not yet implemented");
}
@Test
public void testFunc() throws Exception {
URL url = new URL("http://192.168.0.77:8080/oppo?notify_id=13212&partner_code=c5217trjnrmU6gO5jG8VvUFU0&partner_order=0000001192171129&orders=1100.010000001192171129&pay_result=OK&sign=dNJDN5Ov8FdMZIvLZmnh9rwpKiqwvCzJaja%2B0qpKb3zlFafYxjxCDnNJrtxLqnPOGXHxWZO69onAHzTNfyKZBL3PR57%2F87rwuYk87OthYkIGm4dNunZDnUmMp5m5b0Joe6DOW28NqZETGcKUMeKwQcJmE7c%2FN5aQcWAyazksf0g%3D");
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
OutputStream os = conn.getOutputStream();
//os.write("\r\n".getBytes());
os.close();
Object obj = conn.getContent();
int code = conn.getResponseCode();
System.out.println("code:"+code+", obj:"+obj);
fail("Not yet implemented");
}
@Override
public void run() {
try {
HttpURLConnection request = (HttpURLConnection) new URL("https://api.github.com/repos/TheAndroidMaster/MediaNotification/contributors").openConnection();
request.connect();
JsonReader reader = new JsonReader(new InputStreamReader((InputStream) request.getContent()));
reader.setLenient(true);
reader.beginArray();
reader.skipValue();
while (reader.hasNext()) {
reader.beginObject();
String name = null, imageUrl = null, url = null;
while (reader.hasNext()) {
switch (reader.nextName()) {
case "login":
name = reader.nextString();
break;
case "avatar_url":
imageUrl = reader.nextString();
break;
case "html_url":
url = reader.nextString();
break;
default:
reader.skipValue();
}
}
contributors.add(new ContributorData(name, imageUrl, url));
reader.endObject();
}
reader.endArray();
} catch (Exception ignored) {
}
new Handler(Looper.getMainLooper()).post(new Runnable() {
@Override
public void run() {
AboutDialog dialog = dialogReference.get();
if (dialog != null) {
dialog.contributorView.getAdapter().notifyDataSetChanged();
for (final ContributorData contributor : contributors) {
new ContributorThread(dialog, contributor).start();
}
}
}
});
}
public List<InetAddress> getRemoteSeeds() throws IOException {
HttpURLConnection connection =
(HttpURLConnection) new URL(seedsUrl).openConnection();
connection.setConnectTimeout(1000);
connection.setReadTimeout(10000);
connection.setRequestMethod("GET");
if (connection.getResponseCode() != 200)
throw new RuntimeException("Unable to get data for URL " + seedsUrl);
byte[] b = new byte[2048];
ByteArrayOutputStream bos = new ByteArrayOutputStream();
DataInputStream responseStream = new DataInputStream((FilterInputStream)
connection
.getContent());
int c = 0;
while ((c = responseStream.read(b, 0, b.length)) != -1)
bos.write(b, 0, c);
String response = new String(bos.toByteArray(), Charsets.UTF_8);
LOGGER.info("Retrieved response {} from URL {}", response, seedsUrl);
connection.disconnect();
JSONObject json = (JSONObject) JSONValue.parse(response);
boolean isSeed = (Boolean) json.get("isSeed");
List<String> seedStrings = (json.containsKey("seeds"))
? (List<String>) json.get("seeds") : Collections.emptyList();
List<InetAddress> addresses;
if (isSeed) {
addresses = new ArrayList<>(seedStrings.size() + 1);
addresses.add(getLocalAddress());
} else {
addresses = new ArrayList<>(seedStrings.size());
}
for (String seed : seedStrings) {
addresses.add(InetAddress.getByName(seed));
}
LOGGER.info("Retrieved remote seeds {}", addresses);
return addresses;
}