全部展开
packagewzh.Http;
importjava.io.BufferedReader;
importjava.io.IOException;
import Java.io.input streamreader;
importjava.io.PrintWriter;
importjava.net.URL;
importjava.net.URLConnection;
importjava.util.List;
importjava.util.Map;
公共类http请求{
//*
*向指定的URL发送62616964757 a 686964616 Fe 59 B9 ee7ad 94313363393632 get方法的请求
*
*@paramurl
*发送请求的URL
*@paramparam
*请求参数。 请求参数的格式必须为name1=value1name2=value2。
*@returnURL表示的远程资源的响应结果
*/
publicstaticstringsendget (字符串URL,字符串参数) {
字符串结果=' ';
BufferedReaderin=null;
try{
StringurlNameString=url '? param;
URL realurl=newurl (URL name string;
打开与//URL的连接
urlconnectionconnection=realurl.open connection (;
//设置通用请求属性
connection.setrequestproperty (' accept ',' */* ' );
connection.setrequestproperty (' connection ',' Keep-Alive ' );
connection.setrequestproperty (' user-agent ',
' Mozilla/4.0 (兼容; MSIE6.0; WindowsNT5.1; SV1 () );
//建立实际连接
connection.connect (;
//获取所有响应标头字段
map map=connection.get header fields (;
//巡视所有响应标头字段
for(stringkey:map.keyset ) ) () ) ) )。
system.out.println (key '---- ' map.get );
}
定义缓冲读取器输入流以读取URL响应
in=newbufferedreader (newinputstreamreader (
connection.getInputStream (
字符串线;
while((line=in.readline ) )!=空) {
结果=line;
}
}catch(exceptione ) {
system.out.println ('发送get请求时出现异常!' e;
e .打印堆栈跟踪(;
}
使用finally块关闭输入流
法瑞{
try{
if (入!=空) {
in.close (;
}
}catch(exceptione2) {
E2 .打印堆栈跟踪(;
}
}
返回结果;
}
//*
*将开机自检方法请求发送到指定的URL
*
*@paramurl
*发送请求的URL
*@paramparam
*请求参数。 请求参数的格式必须为name1=value1name2=value2。
*@return表示的远程资源的响应结果
*/
publicstaticstringsendpost (字符串URL,字符串参数)。
打印机写入器out=null;
BufferedReaderin=null;
字符串结果=' ';
try{
URLrealurl=newurl(URL;
打开与//URL的连接
urlconnectionconn=realurl.open connection (;
//设置通用请求属性
conn.setrequestproperty (' accept ',' */* ' );
conn.setrequestproperty (' connection ',' Keep-Alive ' );
conn.setrequestproperty (' user-agent ',
' Mozilla/4.0 (兼容; MSIE6.0; WindowsNT5.1; SV1 () );
发送POST请求需要设定以下两行
Conn.setdooutput(true;
Conn.setdoinput(true;
获取与URLConnection对象相对应的输出流
out=new printwriter (conn.get output stream ();
//发送请求参数
out.print(param;
//flush输出流的缓冲
out.flush (;
定义缓冲读取器输入流以读取URL响应
in=newBufferedReader (
newinputstreamreader (conn.get inputstream () );
字符串线;
while((line=in.readline ) )!=空) {
结果=line;
}
}catch(exceptione ) {
system.out.println ('发送开机自检请求时出现异常!' e;
e .打印堆栈跟踪(;
}
使用finally块关闭输出流、输入流
法瑞{
try{
if (出局!=空) {
out.close (;
}
if (入!=空) {
in.close (;
}
}
catch(ioexceptionex ) {
ex.printStackTrace (;
}
}
返回结果;
}
}
publicstaticvoidmain (字符串[ ] args ) {
发送//get请求
strings=http request.send get (http://localhost :6144/home/requeststring ),) key=123v=456 );
系统. out.println (s;
发送开机自检请求
stringsr=http request.send post (http://localhost 33606144/home/request post string ),(key=123v=456 );
system.out.println(Sr;
}