下面列出了java.net.URL#openConnection ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Test
@TestJetty
public void testJetty() throws Exception {
Context context = new Context();
context.setContextPath("/");
context.addServlet(MyServlet.class, "/bar");
Server server = TestJettyHelper.getJettyServer();
server.addHandler(context);
server.start();
URL url = new URL(TestJettyHelper.getJettyURL(), "/bar");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
assertEquals(conn.getResponseCode(), HttpURLConnection.HTTP_OK);
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
assertEquals(reader.readLine(), "foo");
reader.close();
}
/** access a url, ignoring some IOException such as the page does not exist */
static void access(String urlstring) throws IOException {
LOG.warn("access " + urlstring);
URL url = new URL(urlstring);
URLConnection connection = url.openConnection();
connection.connect();
try {
BufferedReader in = new BufferedReader(new InputStreamReader(
connection.getInputStream()));
try {
for(; in.readLine() != null; );
} finally {
in.close();
}
} catch(IOException ioe) {
LOG.warn("urlstring=" + urlstring, ioe);
}
}
/**
* Disconnect with Maximo Server
* @throws IOException
*/
public void disconnect() throws IOException {
String logout = this.options.getPublicURI()
+ "/logout";
if(this.getOptions().isMultiTenancy()){
logout += "?&_tenantcode=" + this.getOptions().getTenantCode();
}
logger.fine(logout);
URL httpURL = new URL(logout);
// long t1 = System.currentTimeMillis();
HttpURLConnection con = (HttpURLConnection) httpURL.openConnection();
con.setRequestMethod("GET");
this.setCookiesForSession(con);
lastResponseCode = con.getResponseCode();
if (lastResponseCode == 401) {
logger.fine("Logout");
}
this.valid = false;
}
public static void main(String[] args) throws Exception {
initialize();
fileUpload();
//http://flameupload.com/process.php?upload_id=cf3feacdebff8f722a5a4051ccefda3f
u = new URL("http://flameupload.com/process.php?upload_id=" + uploadid);
uc = (HttpURLConnection) u.openConnection();
System.out.println(uc.getURL());
uc.setRequestProperty("Referer", "http://flameupload.com/cgi/ubr_upload.pl?upload_id=" + uploadid);
br = new BufferedReader(new InputStreamReader(uc.getInputStream()));
String temp = "", k = "";
while ((temp = br.readLine()) != null) {
// NULogger.getLogger().info(temp);
System.out.println(temp);
k += temp;
}
System.exit(0);
downloadlink = parseResponse(k, "files/", "\"");
downloadlink = "http://flameupload.com/files/" + downloadlink;
NULogger.getLogger().log(Level.INFO, "Download link : {0}", downloadlink);
}
/**
* This method returns the entire result from the HTTP response.
*
* @param url The URL to fetch the HTTP response from.
* @return The contents of the HTTP response.
* @throws IOException Related to network and stream reading
*/
public static String getResponseFromHttpUrl(URL url) throws IOException {
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
try {
InputStream in = urlConnection.getInputStream();
Scanner scanner = new Scanner(in);
scanner.useDelimiter("\\A");
boolean hasInput = scanner.hasNext();
if (hasInput) {
return scanner.next();
} else {
return null;
}
} finally {
urlConnection.disconnect();
}
}
/**
* Returns the response from the given URL as an array of lines.
* @param url
* The url to connect to.
* @return
* A response string from the server.
* @throws Exception
* This exception is thrown when there was a problem connecting to the URL
*/
public static String[] getText(String url) throws Exception {
URL website = new URL(url);
URLConnection connection = website.openConnection();
BufferedReader in = new BufferedReader(
new InputStreamReader(
connection.getInputStream()));
ArrayList<String> lines = new ArrayList<String>();
String inputLine;
while ((inputLine = in.readLine()) != null)
lines.add(inputLine);
in.close();
return lines.toArray(new String[lines.size()]);
}
private JSONObject getRemainingResource(Project project) throws IOException {
URL url = new URL("https://api.github.com/rate_limit");
HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
connection.setRequestProperty("Authorization", "token " + ((GitHubRepository) project).getToken());
connection.connect();
InputStream is = connection.getInputStream();
BufferedReader bufferReader = new BufferedReader(new InputStreamReader(is, Charset.forName(UTF8)));
String jsonText = readAll(bufferReader);
JSONObject obj = (JSONObject) JSONValue.parse(jsonText);
return (JSONObject) obj.get("resources");
}
private static TestResponse executeRequest(String method, String path) throws IOException {
URL url = new URL("http://localhost:8080" + path);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod(method);
connection.setDoOutput(true);
connection.connect();
String body = IOUtils.toString(connection.getInputStream());
return new TestResponse(connection.getResponseCode(), body);
}
/**
* 下载文件
*
* @param destUrl
* @param fileName
* @throws IOException
*/
public static void downloadFile(String destUrl, String fileName) throws IOException {
byte[] buf = new byte[1024];
int size = 0;
URL url = new URL(destUrl);
HttpURLConnection httpUrl = (HttpURLConnection) url.openConnection();
httpUrl.connect();
try (BufferedInputStream bis = new BufferedInputStream(httpUrl.getInputStream()); FileOutputStream fos = new FileOutputStream(fileName)) {
while ((size = bis.read(buf)) != -1) {
fos.write(buf, 0, size);
}
}
httpUrl.disconnect();
}
public final List<Class<?>> getClassList() {
List<Class<?>> classList = new ArrayList<Class<?>>();
try {
// 从包名获取 URL 类型的资源
Enumeration<URL> urls = ClassUtil.getClassLoader().getResources(packageName.replace(".", "/"));
// 遍历 URL 资源
while (urls.hasMoreElements()) {
URL url = urls.nextElement();
if (url != null) {
// 获取协议名(分为 file 与 jar)
String protocol = url.getProtocol();
if (protocol.equals("file")) {
// 若在 class 目录中,则执行添加类操作
String packagePath = url.getPath().replaceAll("%20", " ");
addClass(classList, packagePath, packageName);
} else if (protocol.equals("jar")) {
// 若在 jar 包中,则解析 jar 包中的 entry
JarURLConnection jarURLConnection = (JarURLConnection) url.openConnection();
JarFile jarFile = jarURLConnection.getJarFile();
Enumeration<JarEntry> jarEntries = jarFile.entries();
while (jarEntries.hasMoreElements()) {
JarEntry jarEntry = jarEntries.nextElement();
String jarEntryName = jarEntry.getName();
// 判断该 entry 是否为 class
if (jarEntryName.endsWith(".class")) {
// 获取类名
String className = jarEntryName.substring(0, jarEntryName.lastIndexOf(".")).replaceAll("/", ".");
// 执行添加类操作
doAddClass(classList, className);
}
}
}
}
}
} catch (Exception e) {
logger.error("获取类出错!", e);
}
return classList;
}
private Bitmap getBitmapFromURL(String strURL) {
try {
URL url = new URL(strURL);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
return BitmapFactory.decodeStream(input);
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
@Test
public void validAcceptHeader() throws Exception {
URL url = new URL(SERVICE_URI + "ESAllPrim");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod(HttpMethod.GET.name());
connection.setRequestProperty(HttpHeader.ACCEPT, "application/json");
connection.connect();
assertEquals(HttpStatusCode.OK.getStatusCode(), connection.getResponseCode());
final String content = IOUtils.toString(connection.getInputStream());
assertNotNull(content);
}
private HttpURLConnection makePreSignedRequest(String method, String preSignedUrl, Map headers) throws IOException {
URL url = new URL(preSignedUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod(method);
addHeaders(connection, headers);
return connection;
}
public VersionInfo(Class<?> classInJar, String groupId, String artifactId, String gitPropertiesResource)
{
try {
URL res = classInJar.getResource(classInJar.getSimpleName() + ".class");
URLConnection conn = res.openConnection();
if (conn instanceof JarURLConnection) {
Manifest mf = ((JarURLConnection)conn).getManifest();
Attributes mainAttribs = mf.getMainAttributes();
String builtBy = mainAttribs.getValue("Built-By");
if (builtBy != null) {
this.user = builtBy;
}
}
Enumeration<URL> resources = classInJar.getClassLoader().getResources("META-INF/maven/" + groupId + "/" + artifactId + "/pom.properties");
while (resources.hasMoreElements()) {
Properties pomInfo = new Properties();
pomInfo.load(resources.nextElement().openStream());
String v = pomInfo.getProperty("version", "unknown");
this.version = v;
}
resources = VersionInfo.class.getClassLoader().getResources(gitPropertiesResource);
while (resources.hasMoreElements()) {
Properties gitInfo = new Properties();
gitInfo.load(resources.nextElement().openStream());
String commitAbbrev = gitInfo.getProperty("git.commit.id.abbrev", "unknown");
String branch = gitInfo.getProperty("git.branch", "unknown");
this.revision = "rev: " + commitAbbrev + " branch: " + branch;
this.date = gitInfo.getProperty("git.build.time", this.date);
this.user = gitInfo.getProperty("git.build.user.name", this.user);
break;
}
} catch (IOException e) {
org.slf4j.LoggerFactory.getLogger(VersionInfo.class).error("Failed to read version info", e);
}
}
@Test
public void testBaseTypeDerivedTypeCasting2() throws Exception {
URL url = new URL(SERVICE_URI + "ESTwoPrim(111)/olingo.odata.test1.ETBase/AdditionalPropertyString_5");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod(HttpMethod.GET.name());
connection.setRequestProperty(HttpHeader.ACCEPT, "application/json");
connection.connect();
assertEquals(HttpStatusCode.OK.getStatusCode(), connection.getResponseCode());
final String content = IOUtils.toString(connection.getInputStream());
assertTrue(content.contains("\"TEST A 0815\""));
}
private InputStream getUrlInputStream(String path) throws MalformedURLException, IOException {
URL url = new URL(path);
URLConnection con = url.openConnection();
return con.getInputStream();
}
@Override
protected String doInBackground(String... params){
String stringUrl = params[0];
String firstName = params[1];
String lastName = params[2];
String email = params[3];
String password = params[4];
int yearOfBirth = Integer.parseInt(params[5]);
JSONObject myjson = new JSONObject();
try {
myjson.put("user_first_name", firstName);
myjson.put("user_last_name", lastName);
myjson.put("user_email", email);
myjson.put("user_password", password);
myjson.put("user_year_birth", yearOfBirth);
URL url = new URL(stringUrl+getPostDataString(myjson));
HttpsURLConnection connection =(HttpsURLConnection) url.openConnection();
connection.setRequestMethod(REQUEST_METHOD);
connection.setReadTimeout(READ_TIMEOUT);
connection.setConnectTimeout(CONNECTION_TIMEOUT);
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("Accept", "application/json");
connection.setDoOutput(true);
connection.setDoInput(true);
String body = myjson.toString();
OutputStream outputStream = new BufferedOutputStream(connection.getOutputStream());
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream, "utf-8"));
writer.write(body);
writer.flush();
writer.close();
outputStream.close();
connection.connect();
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
connection.disconnect();
return response.toString();
}
catch(Exception e) {
return "Exception: " + e.getMessage();
}
}
private InputStream contactURL(String url) throws IOException {
URL urlObj = new URL(url);
URLConnection conn = urlObj.openConnection();
return conn.getInputStream();
}
/**
* Opens and returns a connection to the given URL.
* <p>The default implementation uses the given {@linkplain #setProxy(java.net.Proxy) proxy} -
* if any - to open a connection.
* @param url the URL to open a connection to
* @param proxy the proxy to use, may be {@code null}
* @return the opened connection
* @throws IOException in case of I/O errors
*/
protected HttpURLConnection openConnection(URL url, @Nullable Proxy proxy) throws IOException {
URLConnection urlConnection = (proxy != null ? url.openConnection(proxy) : url.openConnection());
if (!HttpURLConnection.class.isInstance(urlConnection)) {
throw new IllegalStateException("HttpURLConnection required for [" + url + "] but got: " + urlConnection);
}
return (HttpURLConnection) urlConnection;
}
/**
* Get the contents of a <code>URL</code> as a <code>byte[]</code>.
*
* @param url the <code>URL</code> to read
* @return the requested byte array
* @throws NullPointerException if the input is null
* @throws IOException if an I/O exception occurs
* @since 2.4
*/
public static byte[] toByteArray(URL url) throws IOException {
URLConnection conn = url.openConnection();
try {
return IOUtils.toByteArray(conn);
} finally {
close(conn);
}
}