下面列出了java.net.HttpURLConnection#connect ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* <b>MKDIRS</b>
*
* curl -i -X PUT
* "http://<HOST>:<PORT>/<PATH>?op=MKDIRS[&permission=<OCTAL>]"
*
* @param path
* @return
* @throws AuthenticationException
* @throws IOException
* @throws MalformedURLException
*/
public String mkdirs(String path) throws MalformedURLException,
IOException, AuthenticationException {
String resp = null;
ensureValidToken();
HttpURLConnection conn = authenticatedURL
.openConnection(
new URL(new URL(httpfsUrl), MessageFormat.format(
"/webhdfs/v1/{0}?delegation="+delegation+"&op=MKDIRS",
URLUtil.encodePath(path))), token);
conn.setRequestMethod("PUT");
conn.connect();
resp = result(conn, true);
conn.disconnect();
return resp;
}
/**
* Talks to the http interface to create a file.
*
* @param filename The file to create
* @param perms The permission field, if any (may be null)
* @throws Exception
*/
private void createWithHttp ( String filename, String perms )
throws Exception {
String user = HadoopUsersConfTestHelper.getHadoopUsers()[0];
// Remove leading / from filename
if ( filename.charAt(0) == '/' ) {
filename = filename.substring(1);
}
String pathOps;
if ( perms == null ) {
pathOps = MessageFormat.format(
"/webhdfs/v1/{0}?user.name={1}&op=CREATE",
filename, user);
} else {
pathOps = MessageFormat.format(
"/webhdfs/v1/{0}?user.name={1}&permission={2}&op=CREATE",
filename, user, perms);
}
URL url = new URL(TestJettyHelper.getJettyURL(), pathOps);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.addRequestProperty("Content-Type", "application/octet-stream");
conn.setRequestMethod("PUT");
conn.connect();
Assert.assertEquals(HttpURLConnection.HTTP_CREATED, conn.getResponseCode());
}
public int put(String restServiceUrl, Map<String, Object> attributes) throws IOException
{
HttpURLConnection connection = createConnection("PUT", restServiceUrl, _cookies);
try
{
connection.connect();
if (attributes != null)
{
ObjectMapper mapper = new ObjectMapper();
mapper.writeValue(connection.getOutputStream(), attributes);
}
checkResponseCode(connection);
return connection.getResponseCode();
}
finally
{
connection.disconnect();
}
}
@Override
public InputStream getInputStream() throws IOException {
URL url = new URL(this.url);
connection = (HttpURLConnection) url.openConnection();
connection.setConnectTimeout(10000);
connection.setDoInput(true);
connection.addRequestProperty("Connection", "Keep-Alive");
if (connection instanceof HttpsURLConnection) {
HttpsURLConnection httpsURLConnection = (HttpsURLConnection) connection;
httpsURLConnection.setHostnameVerifier(DO_NOT_VERIFY);
httpsURLConnection.setSSLSocketFactory(sslContext.getSocketFactory());
}
connection.connect();
int responseCode = connection.getResponseCode();
if (responseCode == 200) {
inputStream = connection.getInputStream();
return inputStream;
} else {
throw new HttpResponseCodeException(responseCode);
}
}
/**
* It will upload bytes in range [start,end] to Google drive.
*
* @param start
* starting byte of range
* @param end
* ending byte of range
*/
void uploadPartially(@NotNull byte[] buffer, long start, long end) {
String contentRange = "bytes " + start + "-" + end + "/" + downloadFileInfo.getContentLength();
int statusCode;
try {
HttpURLConnection uploadConnection = (HttpURLConnection) createdFileUrl.openConnection();
uploadConnection.setDoOutput(true);
uploadConnection.setRequestProperty("User-Agent", USER_AGENT);
uploadConnection.setRequestProperty("Content-Range", contentRange);
IOUtils.copy(new ByteArrayInputStream(buffer), uploadConnection.getOutputStream());
uploadConnection.connect();
statusCode = uploadConnection.getResponseCode();
} catch (IOException e) {
throw new RuntimeException("Error While uploading file.", e);
}
// In case of successful upload, status code will be 3** or 2**
if (statusCode < 400)
uploadInformation.setUploadedSize(end + 1);
else if (statusCode == 403) {
throw new RuntimeException(
"Google didn't allow us to create file. Your drive might not have enough space.");
}
}
private String readGceMetadata(String path) {
String value = "";
HttpURLConnection connection = connectionFactory.apply(path);
try {
connection.connect();
int responseCode = connection.getResponseCode();
if (responseCode < 200 || responseCode > 299) {
logger.atWarning().log(
"Got an error response: %d\n%s",
responseCode,
CharStreams.toString(new InputStreamReader(connection.getErrorStream(), UTF_8)));
} else {
value = CharStreams.toString(new InputStreamReader(connection.getInputStream(), UTF_8));
}
} catch (IOException e) {
logger.atWarning().withCause(e).log("Cannot obtain GCE metadata from path %s", path);
}
return value;
}
/**
* <b>GETFILECHECKSUM</b>
*
* curl -i "http://<HOST>:<PORT>/webhdfs/v1/<PATH>?op=GETFILECHECKSUM"
*
* @param path
* @return
* @throws MalformedURLException
* @throws IOException
* @throws AuthenticationException
*/
public String getFileCheckSum(String path) throws MalformedURLException,
IOException, AuthenticationException {
String resp = null;
ensureValidToken();
HttpURLConnection conn = authenticatedURL.openConnection(
new URL(new URL(httpfsUrl), MessageFormat.format(
"/webhdfs/v1/{0}?delegation="+delegation+"&op=GETFILECHECKSUM",
URLUtil.encodePath(path))), token);
conn.setRequestMethod("GET");
conn.connect();
resp = result(conn, true);
conn.disconnect();
return resp;
}
public MasterTemplateLoader load() {
try {
HttpURLConnection urlConnection = (HttpURLConnection) new URL(url).openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setRequestProperty("-Xcloudnet-user", simpledUser.getUserName());
urlConnection.setRequestProperty("-Xcloudnet-token", simpledUser.getApiToken());
urlConnection.setRequestProperty("-Xmessage", customName != null ? "custom" : "template");
urlConnection.setRequestProperty("-Xvalue", customName != null ? customName : new Document("template",
template.getName()).append("group",
group)
.convertToJsonString());
urlConnection.setUseCaches(false);
urlConnection.connect();
if (urlConnection.getHeaderField("-Xresponse") == null) {
Files.copy(urlConnection.getInputStream(), Paths.get(dest));
}
urlConnection.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
return this;
}
/**
* Connect to the remote server.
*/
private void connect() {
try {
URL url = new URL(this.endpoint);
connection = (HttpURLConnection) url.openConnection();
connection.setReadTimeout(this.readTimeoutMs);
connection.setConnectTimeout(this.connectTimeoutMs);
connection.setRequestMethod(this.method.name());
if (method == HttpMethod.POST || method == HttpMethod.PUT) {
connection.setDoOutput(true);
} else {
connection.setDoOutput(false);
}
connection.setDoInput(true);
connection.setUseCaches(false);
for (String headerName : headers.keySet()) {
String headerValue = headers.get(headerName);
connection.setRequestProperty(headerName, headerValue);
}
connection.connect();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@Override
protected String doInBackground(Void... params) {
String result = null;
HttpURLConnection connection = null;
try {
connection = NetCipher.getHttpURLConnection(this.urlString);
connection.setRequestMethod("HEAD");
connection.setInstanceFollowRedirects(false);
// gzip encoding seems to cause problems
// https://code.google.com/p/android/issues/detail?id=24672
connection.setRequestProperty("Accept-Encoding", "");
connection.connect();
connection.getResponseCode(); // this actually makes it go
String uriString = connection.getHeaderField("Location");
if (!TextUtils.isEmpty(uriString)) {
GeoParsedPoint point = GeoPointParserUtil.parse(uriString);
if (point != null)
result = point.getGeoUriString();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (connection != null)
connection.disconnect();
}
return result;
}
private static void sendToDiscord(final String webhookUrl, final String message) throws Exception {
final StringBuilder sb = new StringBuilder();
JsonUtils.quoteAsString(message, sb);
final String jsonPostBody = String.format("{\"content\": \"%s\"}", sb);
final java.net.URL url = new java.net.URL(webhookUrl);
final URLConnection con = url.openConnection();
final HttpURLConnection http = (HttpURLConnection) con;
http.setRequestMethod("POST");
http.setDoOutput(true);
final byte[] out = jsonPostBody.getBytes(StandardCharsets.UTF_8);
final int length = out.length;
http.setFixedLengthStreamingMode(length);
http.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
try {
http.connect();
try (OutputStream os = http.getOutputStream()) {
os.write(out);
}
}
catch (Exception e) {
LOGGER.error(e);
}
}
@Test
public void queryInOperatorOnNavProperty() throws Exception {
URL url = new URL(SERVICE_URI + "ESKeyNav?$filter=PropertyCompTwoPrim/"
+ "PropertyInt16%20in%20NavPropertyETKeyNavOne/CollPropertyInt16");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod(HttpMethod.GET.name());
connection.setRequestProperty(HttpHeader.ACCEPT, "application/json;odata.metadata=minimal");
connection.connect();
assertEquals(HttpStatusCode.OK.getStatusCode(), connection.getResponseCode());
assertEquals(ContentType.JSON, ContentType.create(connection.getHeaderField(HttpHeader.CONTENT_TYPE)));
final String content = IOUtils.toString(connection.getInputStream());
assertTrue(content.contains("\"value\":[]"));
}
/**
* 下载对应url下的apk文件
*/
private void downloadAPK() throws Exception {
FileOutputStream fos = new FileOutputStream(apkFile);
String path = updateInfo.apkUrl;
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5000);
conn.setReadTimeout(5000);
conn.setRequestMethod("GET");
conn.connect();
if (conn.getResponseCode() == 200) {
InputStream is = conn.getInputStream();
dialog.setMax(conn.getContentLength());
byte[] buffer = new byte[1024];
int len;
while ((len = is.read(buffer)) != -1) {
fos.write(buffer, 0, len);
dialog.incrementProgressBy(len);
Thread.sleep(2);
}
// 暂且使用throws的方式处理异常了
is.close();
fos.close();
} else {
handler.sendEmptyMessage(WHAT_DOWNLOAD_FAIL);
}
// 关闭连接
conn.disconnect();
}
@Test
public void testWebAppProxyInStandAloneMode() throws YarnException,
InterruptedException, IOException {
conf.setBoolean(YarnConfiguration.AUTO_FAILOVER_ENABLED, false);
WebAppProxyServer webAppProxyServer = new WebAppProxyServer();
try {
conf.set(YarnConfiguration.PROXY_ADDRESS, "0.0.0.0:9099");
cluster.init(conf);
cluster.start();
getAdminService(0).transitionToActive(req);
assertFalse("RM never turned active", -1 == cluster.getActiveRMIndex());
verifyConnections();
webAppProxyServer.init(conf);
// Start webAppProxyServer
Assert.assertEquals(STATE.INITED, webAppProxyServer.getServiceState());
webAppProxyServer.start();
Assert.assertEquals(STATE.STARTED, webAppProxyServer.getServiceState());
// send httpRequest with fakeApplicationId
// expect to get "Not Found" response and 404 response code
URL wrongUrl = new URL("http://0.0.0.0:9099/proxy/" + fakeAppId);
HttpURLConnection proxyConn = (HttpURLConnection) wrongUrl
.openConnection();
proxyConn.connect();
verifyResponse(proxyConn);
explicitFailover();
verifyConnections();
proxyConn.connect();
verifyResponse(proxyConn);
} finally {
webAppProxyServer.stop();
}
}
@Test
public void boundFunctionOverload() throws Exception {
URL url = new URL(SERVICE_URI + "ESTwoKeyNav/olingo.odata.test1.BFC_RTESTwoKeyNav_()");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod(HttpMethod.GET.name());
connection.setRequestProperty(HttpHeader.ACCEPT, "application/json");
connection.connect();
assertEquals(HttpStatusCode.OK.getStatusCode(), connection.getResponseCode());
String content = IOUtils.toString(connection.getInputStream());
assertNotNull(content);
connection.disconnect();
}
@Test
public void validFormatWithIncorrectAcceptCharsetHeader() throws Exception {
URL url = new URL(SERVICE_URI + "ESAllPrim?$format=json");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod(HttpMethod.GET.name());
connection.setRequestProperty(HttpHeader.ACCEPT_CHARSET, "utf<8");
connection.connect();
assertEquals(HttpStatusCode.BAD_REQUEST.getStatusCode(), connection.getResponseCode());
final String content = IOUtils.toString(connection.getErrorStream());
assertTrue(content.contains("The Accept charset header 'utf<8' is not supported."));
}
/**
* 发送http请求取得返回的输入流
* @param requestUrl 请求地址
* @return InputStream
* @throws IOException
*/
public static InputStream httpRequestIO(String requestUrl) throws IOException {
URL url = new URL(requestUrl);
HttpURLConnection httpUrlConn = (HttpURLConnection) url.openConnection();
httpUrlConn.setDoInput(true);
httpUrlConn.setRequestMethod("GET");
httpUrlConn.connect();
// 获得返回的输入流
InputStream inputStream = httpUrlConn.getInputStream();
return inputStream;
}
@Scheduled(fixedDelay = 30 * 1000)//Every 30 seconds
public void refreshPlexUsers() throws IOException {
PlexAuthentication plexAuthConfig = configuration.getAuthentication().getPlex();
if(new Date().getTime()-lastUpdate>+(plexAuthConfig.getRefresh()*1000)) {
List<String> allowedUsers = new ArrayList();
allowedUsers.add(plexAuthConfig.getAdminUser());
URL url = new URL(String.format("https://%s:%[email protected]/api/users", URLEncoder.encode(plexAuthConfig.getAdminUser(), "UTF-8"), URLEncoder.encode(plexAuthConfig.getAdminPass(), "UTF-8")));
HttpURLConnection connection = createConnection(url);
connection.connect();
if (connection.getResponseCode() != 200) {
throw new IOException("unexpected error when getting users list:" + connection.getResponseCode());
}
Document dom = newDocumentFromInputStream(connection.getInputStream());
NodeList users = dom.getElementsByTagName("User");
for (int i = 0; i < users.getLength(); i++) {
Element userEl = (Element) users.item(i);
NodeList servers = userEl.getElementsByTagName("Server");
if (servers.getLength() > 0) {
for (int j = 0; j < servers.getLength(); j++) {
Element server = (Element) servers.item(j);
if (server.getAttribute("name").equals(plexAuthConfig.getServerName())) {
allowedUsers.add(userEl.getAttribute("username").toLowerCase());
}
}
}
}
this.lastUpdate=new Date().getTime();
this.allowedUsers = allowedUsers;
}
}
@Override
protected String doInBackground(String... params) {
try
{
URL whatismyip = new URL("http://checkip.amazonaws.com");
BufferedReader input = new BufferedReader(new InputStreamReader(whatismyip.openStream()));
ip = input.readLine();
HttpURLConnection connection = (HttpURLConnection) new URL("http://ip-api.com/json/" + ip).openConnection();
connection.setReadTimeout(3000);
connection.setConnectTimeout(3000);
connection.setRequestMethod("GET");
connection.setDoInput(true);
connection.connect();
int responseCode = connection.getResponseCode();
if (responseCode != HttpsURLConnection.HTTP_OK) {
throw new IOException("HTTP error code: " + responseCode);
}
InputStream in = new java.io.BufferedInputStream(connection.getInputStream());
//s=readStream(in,10000);
s=convertStreamToString(in);
jsonObject=new JSONObject(s);
city=jsonObject.getString("city");
isp=jsonObject.getString("org");
state=jsonObject.getString("regionName");
country=jsonObject.getString("country");
Log.d("MainActivity", "Call reached here");
if (in != null) {
// Converts Stream to String with max length of 500.
Log.d("MainActivity call 2", s);
}
} catch (Exception e) {
e.printStackTrace();
}
return s;
}
private String getHttpServerResponse(String url) throws Exception {
URL getUrl = new URL(url);
System.out.println(url);
// ���ƴ�յ�URL�������ӣ�URL.openConnection()�������
// URL�����ͣ����ز�ͬ��URLConnection����Ķ������������ǵ�URL��һ��http�������ʵ���Ϸ��ص���HttpURLConnection
HttpURLConnection connection = (HttpURLConnection) getUrl
.openConnection();
// ����������������ӣ���δ�������
connection.connect();
// ������ݵ���������ʹ��Reader��ȡ���ص����
BufferedReader reader = new BufferedReader(new InputStreamReader(
connection.getInputStream(), "UTF-8"));
StringBuffer lines = new StringBuffer(9082);
String line = "";
while ((line = reader.readLine()) != null) {
lines.append(line).append(System.getProperty("line.separator"));
}
reader.close();
connection.disconnect();
System.out.println(lines.toString());
return lines.toString();
}