首页 > 编程知识 正文

HTML获取JAVA后端发来的数据,java请求https接口

时间:2023-05-04 13:41:56 阅读:36770 作者:1445

第一个:

publicstaticstringgeturlcontent {

/**网络的网址*

URL=null;

/** http连接/

HttpURLConnection httpConn=null;

/**//**输入流/

缓冲读取程序in=null;

StringBuffer sb=new StringBuffer (;

try {

URL=newURL(urlstr;

in=newbufferedreader (newinputstreamreader (URL.open stream )、' GBK ' );

字符串str=null;

while((str=in.readline ) )!=空) {

sb.append(str;

}

}catch(exceptionex ) {

} finally {

try {

if (入!=空) {

in.close (;

}

}catch(ioexceptionex ) {

}

}

String result=sb.toString (;

system.out.println(result );

返回结果;

}

第二个:

//http请求返回json

publicstaticstringhttpgetJSON{

字符串结果=' ';

缓冲读取程序in=null;

try {

String urlNameString=url;

URL realurl=newurl (URL name string;

打开与//URL的连接

urlconnectionconnection=realurl.open connection (;

//设置通用请求属性

//connection.setrequestproperty (' content type ',' utf8 ' );

connection.setreadtimeout(5000;

connection.setrequestproperty (' accept ',' */* ' );

connection.setrequestproperty (' connection ',' Keep-Alive ' );

connection.setrequestproperty (' user-agent ',

' Mozilla/4.0 (兼容; MSIE 6.0; Windows NT 5.1; SV1 () );

//建立实际连接

connection.connect (;

//获取所有响应标头字段

//map map=connection.get header fields (;

定义缓冲读取器输入流以读取URL响应

in=newbufferedreader (newinputstreamreader (

connection.getInputStream ()、' UTF-8 ' ); //防止乱码

字符串线;

while((line=in.readline ) )!=空) {

结果=line;

}

}catch(exceptione ) {

//system.out.println ('发送get请求时出现异常!' e;

e .打印堆栈跟踪(;

result=' ';

}

使用finally块关闭输入流

法瑞{

try {

if (入!=空) {

in.close (;

}

}catch(exceptionE2) {

E2 .打印堆栈跟踪(;

}

}

//system.out.println('123 );

返回结果;

}

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。