-
2014-11-02 00:15:28
JAVA访问URL:
package Test; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.net.URLConnection; import java.awt.Desktop; public class URLTest { public static void main(String[] args) { String urlStr = "http://www.baidu.com"; URL url; try { url = new URL(urlStr); URLConnection URLconnection = url.openConnection(); HttpURLConnection httpConnection = (HttpURLConnection)URLconnection; int responseCode = httpConnection.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { System.err.println("成功"); InputStream urlStream = httpConnection.getInputStream(); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlStream)); String sCurrentLine = ""; String sTotalString = ""; while ((sCurrentLine = bufferedReader.readLine()) != null) { sTotalString += sCurrentLine; } System.err.println(sTotalString); runBroswer(urlStr); }else{ System.err.println("失败"); } } catch (Exception e) { e.printStackTrace(); } } public static void runBroswer(String webSite) { try { Desktop desktop = Desktop.getDesktop(); if (desktop.isDesktopSupported() && desktop.isSupported(Desktop.Action.BROWSE)) { URI uri = new URI(webSite); desktop.browse(uri); } } catch (IOException ex) { ex.printStackTrace(); } catch (URISyntaxException ex) { ex.printStackTrace(); } } }
更多相关内容 -
使用Java访问url的简单操作
2021-02-12 09:40:19使用URL类访问url,传递参数,完成操作。Java代码 StringurlStr="";URLurl=newURL(urlStr);URLConnectionURLconnection=url.openConnection();HttpURLConnectionhttpConnection=(HttpURLConnection)URLconnection;...使用URL类访问url,传递参数,完成操作。
Java代码
String urlStr ="";
URL url =newURL(urlStr);
URLConnection URLconnection = url.openConnection();
HttpURLConnection httpConnection = (HttpURLConnection)URLconnection;
intresponseCode = httpConnection.getResponseCode();
if(responseCode == HttpURLConnection.HTTP_OK) {
}else{
}String urlStr = "";
URL url = new URL(urlStr);
URLConnection URLconnection = url.openConnection();
HttpURLConnection httpConnection = (HttpURLConnection)URLconnection;
int responseCode = httpConnection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
}else{
}
取得该url的页面值(输出值)
Java代码
InputStream urlStream = httpConnection.getInputStream();
BufferedReader bufferedReader =newBufferedReader(newInputStreamReader(urlStream));
String sCurrentLine ="";
String sTotalString ="";
while((sCurrentLine = bufferedReader.readLine()) !=null) {
sTotalString += sCurrentLine;
}
//假设该url页面输出为"OK"
if(sTotalString.equals("OK")) {
}else{
}InputStream urlStream = httpConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlStream));
String sCurrentLine = "";
String sTotalString = "";
while ((sCurrentLine = bufferedReader.readLine()) != null) {
sTotalString += sCurrentLine;
}
//假设该url页面输出为"OK"
if (sTotalString.equals("OK")) {
} else {
}
-
java 访问url
2015-06-29 11:07:07在平时开发中,我们一般都需要实现外部的url,贴上本人开发使用的三种访问代码。希望点评 第一种: public class HttpUtils { public static void main(String[] args) { System.out.println(SMS("", ...在平时开发中,我们一般都需要实现外部的url,贴上本人开发使用的三种访问代码。希望点评
第一种:
第二种,跟第一种类似,进行了细化:public class HttpUtils { public static void main(String[] args) { System.out.println(SMS("", "https://www.baidu.com/")); } private static String SMS(String postData, String postUrl) { try { // 发送POST请求 URL url = new URL(postUrl); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST");//修改发送方式 conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); conn.setRequestProperty("Connection", "Keep-Alive"); conn.setUseCaches(false); conn.setDoOutput(true); conn.setRequestProperty("Content-Length", "" + postData.length()); OutputStreamWriter out = new OutputStreamWriter( conn.getOutputStream(), "UTF-8"); out.write(postData); out.flush(); out.close(); // 获取响应状态 if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) { return ""; } // 获取响应内容体 String line, result = ""; BufferedReader in = new BufferedReader(new InputStreamReader( conn.getInputStream(), "utf-8")); while ((line = in.readLine()) != null) { result += line + "\n"; } in.close(); return result; } catch (IOException e) { } return ""; } }
import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.ProtocolException; import java.net.URL; import java.net.URLEncoder; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; public class HttpUtils { private static final int TIME_OUT = 5; /** * 通过HTTP GET 发送参数 * * @param httpUrl * @param parameter * @param httpMethod */ public static String sendGet(String httpUrl, Map<String, String> parameter) { if (parameter == null || httpUrl == null) { return null; } StringBuilder sb = new StringBuilder(); Iterator<Map.Entry<String, String>> iterator = parameter.entrySet().iterator(); while (iterator.hasNext()) { if (sb.length() > 0) { sb.append('&'); } Entry<String, String> entry = iterator.next(); String key = entry.getKey(); String value; try { value = URLEncoder.encode(entry.getValue(), "UTF-8"); } catch (UnsupportedEncodingException e) { value = ""; } sb.append(key).append('=').append(value); } String urlStr = null; if (httpUrl.lastIndexOf('?') != -1) { urlStr = httpUrl + '&' + sb.toString(); } else { urlStr = httpUrl + '?' + sb.toString(); } HttpURLConnection httpCon = null; String responseBody = null; try { URL url = new URL(urlStr); httpCon = (HttpURLConnection) url.openConnection(); httpCon.setDoOutput(true); httpCon.setRequestMethod("GET"); httpCon.setConnectTimeout(TIME_OUT * 1000); httpCon.setReadTimeout(TIME_OUT * 1000); // 开始读取返回的内容 InputStream in = httpCon.getInputStream(); byte[] readByte = new byte[1024]; // 读取返回的内容 int readCount = in.read(readByte, 0, 1024); ByteArrayOutputStream baos = new ByteArrayOutputStream(); while (readCount != -1) { baos.write(readByte, 0, readCount); readCount = in.read(readByte, 0, 1024); } responseBody = new String(baos.toByteArray(), "UTF-8"); baos.close(); } catch (Exception e) { } finally { if (httpCon != null) httpCon.disconnect(); } return responseBody; } /** * 使用HTTP POST 发送文本 * * @param httpUrl * 发送的地址 * @param postBody * 发送的内容 * @return 返回HTTP SERVER的处理结果,如果返回null,发送失败 */ public static String sentPost(String httpUrl, String postBody) { return sentPost(httpUrl, postBody, "UTF-8", null); } /** * 使用HTTP POST 发送文本 * * @param httpUrl * 发送的地址 * @param postBody * 发送的内容 * @return 返回HTTP SERVER的处理结果,如果返回null,发送失败 */ public static String sentPost(String httpUrl, String postBody, String encoding) { return sentPost(httpUrl, postBody, encoding, null); } /** * 使用HTTP POST 发送文本 * @param httpUrl 目的地址 * @param postBody post的包体 * @param headerMap 增加的Http头信息 * @return */ public static String sentPost(String httpUrl, String postBody, Map<String, String> headerMap) { return sentPost(httpUrl, postBody, "UTF-8", headerMap); } /** * 使用HTTP POST 发送文本 * * @param httpUrl * 发送的地址 * @param postBody * 发送的内容 * @param encoding * 发送的内容的编码 * @param headerMap 增加的Http头信息 * @return 返回HTTP SERVER的处理结果,如果返回null,发送失败 * ................. */ public static String sentPost(String httpUrl, String postBody, String encoding, Map<String, String> headerMap) { HttpURLConnection httpCon = null; String responseBody = null; URL url = null; try { url = new URL(httpUrl); } catch (MalformedURLException e1) { return null; } try { httpCon = (HttpURLConnection) url.openConnection(); } catch (IOException e1) { return null; } if (httpCon == null) { return null; } httpCon.setDoOutput(true); httpCon.setConnectTimeout(TIME_OUT * 1000); httpCon.setReadTimeout(TIME_OUT * 1000); httpCon.setDoOutput(true); httpCon.setUseCaches(false); try { httpCon.setRequestMethod("POST"); } catch (ProtocolException e1) { return null; } if (headerMap != null) { Iterator<Entry<String, String>> iterator = headerMap.entrySet().iterator(); while (iterator.hasNext()) { Entry<String, String> entry = iterator.next(); httpCon.addRequestProperty(entry.getKey(), entry.getValue()); } } OutputStream output; try { output = httpCon.getOutputStream(); } catch (IOException e1) { return null; } try { output.write(postBody.getBytes(encoding)); } catch (UnsupportedEncodingException e1) { return null; } catch (IOException e1) { return null; } try { output.flush(); output.close(); } catch (IOException e1) { return null; } // 开始读取返回的内容 InputStream in; try { in = httpCon.getInputStream(); } catch (IOException e1) { return null; } /** * 这个方法可以在读写操作前先得知数据流里有多少个字节可以读取。 * 需要注意的是,如果这个方法用在从本地文件读取数据时,一般不会遇到问题, * 但如果是用于网络操作,就经常会遇到一些麻烦。 * 比如,Socket通讯时,对方明明发来了1000个字节,但是自己的程序调用available()方法却只得到900,或者100,甚至是0, * 感觉有点莫名其妙,怎么也找不到原因。 * 其实,这是因为网络通讯往往是间断性的,一串字节往往分几批进行发送。 * 本地程序调用available()方法有时得到0,这可能是对方还没有响应,也可能是对方已经响应了,但是数据还没有送达本地。 * 对方发送了1000个字节给你,也许分成3批到达,这你就要调用3次available()方法才能将数据总数全部得到。 * * 经常出现size为0的情况,导致下面readCount为0使之死循环(while (readCount != -1) {xxxx}),出现死机问题 */ int size = 0; try { size = in.available(); } catch (IOException e1) { return null; } if (size == 0) { size = 1024; } byte[] readByte = new byte[size]; // 读取返回的内容 int readCount = -1; try { readCount = in.read(readByte, 0, size); } catch (IOException e1) { return null; } ByteArrayOutputStream baos = new ByteArrayOutputStream(); while (readCount != -1) { baos.write(readByte, 0, readCount); try { readCount = in.read(readByte, 0, size); } catch (IOException e) { return null; } } try { responseBody = new String(baos.toByteArray(), encoding); } catch (UnsupportedEncodingException e) { return null; } finally { if (httpCon != null) { httpCon.disconnect(); } if (baos != null) { try { baos.close(); } catch (IOException e) { } } } return responseBody; } }
第三种,使用httpclient进行访问,需要是到 http://hc.apache.org/下载jar包import java.io.IOException; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.ResponseHandler; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; /** * 根据httpclient进行访问 * @author Administrator * */ public class HttpUtils { /** * 访问url方法 * * @param url * @return */ public static String callOnHttp(String url) { String address = ""; CloseableHttpClient httpclient = HttpClients.createDefault(); try { HttpGet httpget = new HttpGet(url); ResponseHandler<String> responseHandler = new ResponseHandler<String>() { public String handleResponse(final HttpResponse response) throws ClientProtocolException, IOException { int status = response.getStatusLine().getStatusCode(); if (status >= 200 && status < 300) { HttpEntity entity = response.getEntity(); return entity != null ? EntityUtils.toString(entity) : null; } else { throw new ClientProtocolException( "Unexpected response status: " + status); } } }; address = httpclient.execute(httpget, responseHandler); } catch (Exception e) { e.printStackTrace(); } finally { try { httpclient.close(); } catch (IOException e) { e.printStackTrace(); } } return address; } }
-
JAVA访问URL并返回获取的页面数据(爬取指定页面数据)
2019-09-10 16:03:53import java.io.BufferedReader; import java.io.InputStreamReader;...import java.net.URL; import java.net.URLConnection; import java.util.List; import java.util.Map; /** * @Author d...package com.http; import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.URL; import java.net.URLConnection; import java.util.List; import java.util.Map; /** * @Author dp * @Date 2019/9/10 15:43 */ public class HttpTest { public static void main(String[] args) { String url ="https://blog.csdn.net/dongp1994/article/details/100702200"; String param=""; String sendGET = GetUrl(url, param); System.out.println(sendGET); } public static String GetUrl(String url,String param){ String result="";//访问返回结果 BufferedReader read=null;//读取访问结果 try { //创建url URL realurl=new URL(url+"?"+param); //打开连接 URLConnection connection=realurl.openConnection(); // 设置通用的请求属性 connection.setRequestProperty("accept", "*/*"); connection.setRequestProperty("connection", "Keep-Alive"); connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)"); //建立连接 connection.connect(); // 获取所有响应头字段 Map<String, List<String>> map = connection.getHeaderFields(); // 遍历所有的响应头字段,获取到cookies等 for (String key : map.keySet()) { System.out.println(key + "--->" + map.get(key)); } // 定义 BufferedReader输入流来读取URL的响应 read = new BufferedReader(new InputStreamReader( connection.getInputStream(),"UTF-8")); String line;//循环读取 while ((line = read.readLine()) != null) { result += line; } } catch (Exception e) { e.printStackTrace(); }finally{ if(read!=null){//关闭流 try { read.close(); } catch (Exception e) { e.printStackTrace(); } } } return result; } }
-
java 使用URL访问网页
2010-06-21 16:35:45java 使用URL访问网页 java 使用URL访问网页 java 使用URL访问网页 -
Java访问url
2017-09-26 10:04:11try { URL url = new URL("http://baiduu.com"); InputStream in =url.openStream(); InputStreamReader isr = new InputStreamReader(in); BufferedReade -
Java访问URL实现接口测试
2019-03-28 10:58:13httpClient httpConnection httpUnit -
JAVA后台访问url
2018-01-15 11:24:24public static String SendGET(String url,String param){ String result="";//访问返回结果 BufferedReader read=null;//读取访问结果 try { //创建url URL realurl=new ... -
java后台访问网址url
2019-04-10 18:28:44public static JSONObject doGetJson(String url) throws ClientProtocolException, IOException { JSONObject jsonObject =null; DefaultHttpClient client = new DefaultHttpClient()... -
Java访问用户名密码验证的url
2019-02-12 10:39:53Java访问用户名密码验证的url引言代码解释 引言 有些url带有用户名密码,我们直接用curl或者wget访问的时候出现401,没有访问权限。这时我们就需要对url进行必要的权限处理 代码解释 private static String Post1... -
\java通过url在线预览Word、excel、ppt、pdf、txt文档中的内容
2011-08-07 09:29:59\java通过url在线预览Word、excel、ppt、pdf、txt文档中的内容 \java通过url在线预览Word、excel、ppt、pdf、txt文档中的内容 -
JAVA验证URL是否有效连接的方法
2015-12-06 10:26:30昨天做了个监控远程服务器是否正常连接,费了很大脑动力,写成了下面的方法,现在分享给大家,希望可以帮助都更多的人。 写个方法的时候一直有个误区,不知道怎么去监控远程服务器,望遇到同样问题人,跳出这个思想... -
java解决限制访问指定url
2021-04-24 17:36:53当然在这个类中,可以结合现有系统的角色,权限体系做进一步的整合,而MySecurityConfig这个类,控制对访问的URL做保护,规定了哪些URL需要走登录认证,哪些可以不用认证等配置信息 启动项目之后,让我们来做一下... -
JAVA解决URL路径中含有中文的问题
2016-03-11 22:21:04JAVA解决URL路径中含有中文的问题。无论是路径中还是文件名包含中文都可以处理。经测试验证通过。 -
java访问URL并下载文件
2015-01-19 12:50:51package com.venustech.cnnvd.service; import java.io.BufferedInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.net.HttpURLConnection; import java.net.URL; /** -
Java获取当前访问url地址(SpringMVC)
2021-02-12 09:11:42本文地址:http://www.dutycode.com/java_huoqu_dangqian_url.html除非注明,文章均为 www.dutycode.com 原创,欢迎转载!转载请注明本文地址,谢谢。情景:在做微信开发的时候,需要用到签名信息,签名信息是需要... -
java实现通过url实现浏览器下载pdf文件
2020-06-12 08:45:43java实现通过url实现浏览器下载pdf文件 // 下载pdf文件工具类 public static void toDownload(HttpServletRequest request, HttpServletResponse response, Map<String, Object> map) { ServletOutputStream ... -
java后台访问url需要的包——httpclient方式
2015-07-13 11:31:56java后台访问url需要的包,没时间好好整理,包可能多几个 -
JAVA后端,拼接URL访问,特殊字符异常处理
2017-12-07 17:57:02JAVA后端,拼接URL访问,特殊字符异常处理一般来说,前端传入keyword之前都需要进行urlencode处理,详情见链接为什么要用 urlencode()。拿到参数(比如keyword)之后我们可能会需要利用此去拼接其他url,常见的报错... -
Java代码访问url,并返回json串之实现方法
2018-05-29 17:57:49在项目开发中,需要在控制器中访问url接口,并得到json串,将得到的json串用于jsp页面。这里总结一下在java代码中分别进行get和post的url访问。需要准备一下jar包:org.apache.http.HttpEntity;org.apache.... -
根据url下载文件(JAVA实现)
2020-06-17 11:38:581)根据url下载文件 2)情况:由于在线浏览某个文件过大(日志文件),导致浏览器直接加载奔溃,因此想通过程序,将文件下载下来查看 3)代码: import java.io.BufferedInputStream; import java.io.... -
java对URL中含有的特殊字符"&"的处理
2018-07-20 14:11:121、问题描述:最近在做java导出文件到excel项目中遇到请求的URL包含参数&的时候,导出的文件里面内容为空,什么都没有。 2、问题排查:首先我查看项目运行的日志,发现打印出来的错误信息是空指针异常java.... -
Java访问HTTPS类型的URL
2019-05-25 11:49:52在工作中,难免会遇到调用第三...有很多HTTP/HTTPS请求的插件,反正博主在Java中喜欢用okhttp3,关于okhttp3的API这里不再介绍,主要是下面的这个类和创建client的过程。 首先在pom.xml引入依赖: <!-- https:... -
java 判断一个url是否可以访问的方法
2019-06-04 14:56:45有些时候,我们需要判断某个url是否可以访问,可以访问了,才允许继续进行,目前有两种方式,最后使用带超时时间的, 因为第一种超时时间不定,可能会出现阻塞的情况。 package com.url; import java.io.... -
从URL获取数据的几种方式
2021-02-27 18:58:38下面是url.openStream()的源码: public final InputStream openStream() throws java.io.IOException { return openConnection().getInputStream(); } 他也是先通过openConnection()方法获取URLConnection对象,... -
JAVA通过url获取网页内容
2012-12-08 21:50:57JAVA通过url获取网页内容 -
java调用url的两种方式
2015-11-09 17:30:54一、在java中调用url,并打开一个新的窗口 Java代码 String url="http://10.58.2.131:8088/spesBiz/test1.jsp"; String cmd = "cmd.exe /c start " + url; try { Process... -
用java程序直接访问URL地址
2011-10-30 16:24:20/** * 程序中访问http数据接口 */ public static String getURLContent(String urlStr) { /** 网络的url地址 */ URL url = null; /** http连接 */ -
java获取请求url地址
2021-11-12 10:23:22String urlPrefix = String.valueOf(url.substring(0,url.length()-request.getRequestURI().length())); 测试地址:http://127.0.0.1:8080/xxxx urlPrefix 打印结果:http://127.0.0.1:8080 以上仅供参考。