「java提供url」java提供url客户填报信息
本篇文章给大家谈谈java提供url,以及java提供url客户填报信息对应的知识点,希望对各位有所帮助,不要忘了收藏本站喔。
本文目录一览:
- 1、用java怎么写URL接口
- 2、java获取服务器文件,怎样用url返回
- 3、Java如何向外提供接口
- 4、java获取URL
- 5、求用java得到URL相应源文件的方法
- 6、java怎样获取url参数
用java怎么写URL接口
在java中,调用http请求接口,主要通过流的方式进行调用,示例接口如下:
/**
* 程序中访问http数据接口
*/
public String searchLoginService(String urlStr) {
/** 网络的url地址 */
URL url = null;
/** http连接 */
HttpURLConnection httpConn = null;
/**//** 输入流 */
BufferedReader in = null;
StringBuffer sb = new StringBuffer();
try{
url = new URL(urlStr);
in = new BufferedReader( new InputStreamReader(url.openStream(),"UTF-8") );
String str = null;
while((str = in.readLine()) != null) {
sb.append( str );
}
} catch (Exception ex) {
logger.error(ex.getMessage(), ex);
} finally{
try{
if(in!=null) {
in.close();
}
}catch(IOException ex) {
logger.error(ex.getMessage(), ex);
}
}
String result =sb.toString();
System.out.println(result);
return result;
}
java获取服务器文件,怎样用url返回
下面提供二种方法会使用java发送url请求,并获取服务器返回的值
第一种方法:
代码如下:
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.util.EntityUtils;
publicstaticStringsendUrlRequest(StringurlStr,Stringparam1,Stringparam2)throwsException{
StringtempStr=null;
HttpClienthttpclient=newDefaultHttpClient();
Propertiesproperties=newProperties();
HttpEntityentity=null;
StringxmlContent="";
try
{
//设置超时时间
httpclient.getParams().setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT,20000);
httpclient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT,20000);
//封装需要传递的参数
ListNameValuePairnvps=newArrayListNameValuePair();
nvps.add(newBasicNameValuePair("mainMemoCode",strmainMemoCode));
nvps.add(newBasicNameValuePair("recordPassWord",strrecordPassWord));
//客户端的请求方法类型
HttpPosthttpPost=newHttpPost(urlStr);
httpPost.setEntity(newUrlEncodedFormEntity(nvps,"GBK"));
HttpResponseresponse=httpclient.execute(httpPost);
//获取服务器返回Http的Content-Type的值
tempStr=response.getHeaders("Content-Type")[0].getValue().toString();
//获取服务器返回页面的值
entity=response.getEntity();
xmlContent=EntityUtils.toString(entity);
Stringstrmessage=null;
System.out.println(xmlContent);
System.out.println(response.getHeaders("Content-Type")[0].getValue().toString());
httpPost.abort();
}
catch(SocketTimeoutExceptione)
{
}
catch(Exceptionex)
{
ex.printStackTrace();
}
finally{
httpclient.getConnectionManager().shutdown();
}
第二种方法:
代码如下:
publicstaticStringsendUrlRequest(StringurlStr,Stringparam1,Stringparam2)throwsException{
HttpURLConnectionurl_con=null;
try{
URLurl=newURL(urlStr);
StringBufferbankXmlBuffer=newStringBuffer();
//创建URL连接,提交到数据,获取返回结果
HttpURLConnectionconnection=(HttpURLConnection)url.openConnection();
connection.setRequestMethod("POST");
connection.setDoOutput(true);
connection.setRequestProperty("User-Agent","directclient");
PrintWriterout=newPrintWriter(newOutputStreamWriter(connection.getOutputStream(),"GBK"));
out.println(param);
out.close();
BufferedReaderin=newBufferedReader(newInputStreamReader(connection
.getInputStream(),"GBK"));
StringinputLine;
while((inputLine=in.readLine())!=null){
bankXmlBuffer.append(inputLine);
}
in.close();
tempStr=bankXmlBuffer.toString();
}
catch(Exceptione)
{
System.out.println("发送GET请求出现异常!"+e);
e.printStackTrace();
}finally{
if(url_con!=null)
url_con.disconnect();
}
returntmpeStr;
}
总结:多练习代码,熟练之后才能更快速的去了解代码的学习的方法。多去获取一些思维方面的书籍可以看看。
Java如何向外提供接口
public static String sendPostUrl(String url, String param, String charset) {
PrintWriter out = null;
BufferedReader in = null;
String result = "";
try {
URL realUrl = new URL(url);
// 打开和URL之间的连接
URLConnection conn = realUrl.openConnection();
// 设置通用的请求属性
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
// 发送POST请求必须设置如下两行
conn.setDoOutput(true);
conn.setDoInput(true);
// 获取URLConnection对象对应的输出流
out = new PrintWriter(conn.getOutputStream());
// 发送请求参数
out.print(param);
// flush输出流的缓冲
out.flush();
// 定义BufferedReader输入流来读取URL的响应
in = new BufferedReader(new InputStreamReader(conn.getInputStream(), charset));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
System.out.println("发送 POST 请求出现异常!" + e);
e.printStackTrace();
}
// 使用finally块来关闭输出流、输入流
finally {
try {
if (out != null) {
out.close();
}
if (in != null) {
in.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
return result;
}
java获取URL
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
public class GetLinks {
private String webSource;
private String url;
public GetLinks(String url) throws MalformedURLException, IOException {
this.url = Complete(url);
webSource = getWebCon(this.url);
}
private String getWebCon(String strURL) throws MalformedURLException,
IOException {
StringBuffer sb = new StringBuffer();
java.net.URL url = new java.net.URL(strURL);
BufferedReader in = new BufferedReader(new InputStreamReader(url
.openStream()));
String line;
while ((line = in.readLine()) != null) {
sb.append(line);
}
in.close();
return sb.toString();
}
private String Complete(String link)throws MalformedURLException{
URL url1 = new URL(link);
URL url2 = new URL(link+"/");
String handledUrl = link;
try{
StringBuffer sb1 = new StringBuffer();
BufferedReader in1 = new BufferedReader(new InputStreamReader(url1
.openStream()));
String line1;
while ((line1 = in1.readLine()) != null) {
sb1.append(line1);
}
in1.close();
StringBuffer sb2 = new StringBuffer();
BufferedReader in2 = new BufferedReader(new InputStreamReader(url2
.openStream()));
String line2;
while ((line2 = in2.readLine()) != null) {
sb2.append(line2);
}
in1.close();
if(sb1.toString().equals(sb2.toString())){
handledUrl = link+"/";
}
}catch(Exception e){
handledUrl = link;
}
return handledUrl;
}
/**
* 处理链接的相对路径
* @param link 相对路径或绝对路径
* @return 绝对路径
*/
private String urlHandler(String link) {
if (link == null)
return null;
link = link.trim();
if (link.toLowerCase().startsWith("http://")
|| link.toLowerCase().startsWith("https://")) {
return link;
}
String pare = url.trim();
if (!link.startsWith("/")) {
if (pare.endsWith("/")) {
return pare + link;
}
if (url.lastIndexOf("/") == url.indexOf("//") + 1 || url.lastIndexOf("/") == url.indexOf("//") + 2) {
return pare + "/" + link;
} else {
int lastSeparatorIndex = url.lastIndexOf("/");
return url.substring(0, lastSeparatorIndex + 1) + link;
}
}else{
if (url.lastIndexOf("/") == url.indexOf("//") + 1 || url.lastIndexOf("/") == url.indexOf("//") + 2) {
return pare + link;
}else{
return url.substring(0,url.indexOf("/", url.indexOf("//")+3)) + link;
}
}
}
public ListString getAnchorTagUrls() {
if (webSource == null) {
System.out.println("没有网页源代码");
return null;
}
ArrayListString list = new ArrayListString();
int index = 0;
while (index != -1) {
index = webSource.toLowerCase().indexOf("a ", index);
if (index != -1) {
int end = webSource.indexOf("", index);
String str = webSource.substring(index, end == -1 ? webSource
.length() : end);
str = str.replaceAll("\\s*=\\s*", "=");
if (str.toLowerCase().matches("^a.*href\\s*=\\s*[\'|\"]?.*")) {// "^a\\s+\\w*\\s*href\\s*=\\s*[\'|\"]?.*"
int hrefIndex = str.toLowerCase().indexOf("href=");
int leadingQuotesIndex = -1;
if ((leadingQuotesIndex = str.indexOf("\"", hrefIndex
+ "href=".length())) != -1) { // 形如a
// href="....."
int TrailingQuotesIndex = str.indexOf("\"",
leadingQuotesIndex + 1);
TrailingQuotesIndex = TrailingQuotesIndex == -1 ? str
.length() : TrailingQuotesIndex;
str = str.substring(leadingQuotesIndex + 1,
TrailingQuotesIndex);
str = urlHandler(str);
list.add(str);
System.out.println(str);
index += "a ".length();
continue;
}
if ((leadingQuotesIndex = str.indexOf("\'", hrefIndex
+ "href=".length())) != -1) { // 形如a
// href='.....'
int TrailingQuotesIndex = str.indexOf("\'",
leadingQuotesIndex + 1);
TrailingQuotesIndex = TrailingQuotesIndex == -1 ? str
.length() : TrailingQuotesIndex;
str = str.substring(leadingQuotesIndex + 1,
TrailingQuotesIndex);
str = urlHandler(str);
System.out.println(str);
list.add(str);
index += "a ".length();
continue;
}
int whitespaceIndex = str.indexOf(" ", hrefIndex
+ "href=".length()); // 形如a href=
//
whitespaceIndex = whitespaceIndex == -1 ? str.length()
: whitespaceIndex;
str = str.substring(hrefIndex + "href=".length(),
whitespaceIndex);
str = urlHandler(str);
list.add(str);
System.out.println(str);
}
index += "a ".length();
}
}
return list;
}
public static void main(String[] args) throws Exception {
GetLinks gl = new GetLinks("");
ListString list = gl.getAnchorTagUrls();
for(String str:list) {
System.out.println(str);
}
}
}
求用java得到URL相应源文件的方法
Java可以通过链接的mime类型来判断源文件的类型,从而得到源文件内容,示例如下:
URLConnection提供了两种方法可以猜测(根据实测结果,这个猜测是相当的准)数据的MIME类型。
第一个是:
public static String guessContentTypeFromName(String name)
这个方法根据URL文件部分的后缀名来判断类型,跟之前我的方法一样。这个不能解决上面那个问题。
第二个是:public static String guessContentTypeFromStream(InputStream in)
这个方法是根据流的前面几个字节来判断类型,这个就不需要文件后缀名了,完全可以解决上面那个问题。
测试代码如下:BufferedInputStream bis = null;HttpURLConnection urlconnection = null;URL url = null; url = new URL(strUrl); urlconnection = (HttpURLConnection) url.openConnection(); urlconnection.connect();bis = new BufferedInputStream(urlconnection.getInputStream()); System.out.println("file type:"+HttpURLConnection.guessContentTypeFromStream(bis));
java怎样获取url参数
如果是javaweb 项目,那么非常简单,直接调用 HttpServletRequest 对象的 .getParamter("参数名称") 方法即可得到。
如果是普通java 项目:
/**
* 获取网址的指定参数值
*
* @param url
* 网址
* @param parameter
* 参数名称
* @author cevencheng
* @return
*/
public static String getParameter(String url, String parameter, String defaultValue) {
try {
final String charset = "utf-8";
url = URLDecoder.decode(url, charset);
if (url.indexOf('?') != -1) {
final String contents = url.substring(url.indexOf('?') + 1);
HashMapString, String map = new HashMapString, String();
String[] keyValues = contents.split("");
for (int i = 0; i keyValues.length; i++) {
String key = keyValues[i].substring(0, keyValues[i].indexOf("="));
String value = keyValues[i].substring(keyValues[i].indexOf("=") + 1);
if (key.equals(parameter)) {
if (value == null || "".equals(value.trim())) {
return defaultValue;
}
return value;
}
map.put(key, value);
}
}
return null;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
java提供url的介绍就聊到这里吧,感谢你花时间阅读本站内容,更多关于java提供url客户填报信息、java提供url的信息别忘了在本站进行查找喔。