您好,欢迎访问三七文档
当前位置:首页 > IT计算机/网络 > Java > java发送http的get、post请求
packagewzh.Http;importjava.io.BufferedReader;importjava.io.IOException;importjava.io.InputStreamReader;importjava.io.PrintWriter;importjava.net.URL;importjava.net.URLConnection;importjava.util.List;importjava.util.Map;publicclassHttpRequest{/***向指定URL发送GET方法的请求**@paramurl*发送请求的URL*@paramparam*请求参数,请求参数应该是name1=value1&name2=value2的形式。*@returnURL所代表远程资源的响应结果*/publicstaticStringsendGet(Stringurl,Stringparam){Stringresult=;BufferedReaderin=null;try{StringurlNameString=url+?+param;URLrealUrl=newURL(urlNameString);//打开和URL之间的连接URLConnectionconnection=realUrl.openConnection();//设置通用的请求属性connection.setRequestProperty(accept,*/*);connection.setRequestProperty(connection,Keep-Alive);connection.setRequestProperty(user-agent,Mozilla/4.0(compatible;MSIE6.0;WindowsNT5.1;SV1));//建立实际的连接connection.connect();//获取所有响应头字段MapString,ListStringmap=connection.getHeaderFields();//遍历所有的响应头字段for(Stringkey:map.keySet()){System.out.println(key+---+map.get(key));}//定义BufferedReader输入流来读取URL的响应in=newBufferedReader(newInputStreamReader(connection.getInputStream()));Stringline;while((line=in.readLine())!=null){result+=line;}}catch(Exceptione){System.out.println(发送GET请求出现异常!+e);e.printStackTrace();}//使用finally块来关闭输入流finally{try{if(in!=null){in.close();}}catch(Exceptione2){e2.printStackTrace();}}returnresult;}/***向指定URL发送POST方法的请求**@paramurl*发送请求的URL*@paramparam*请求参数,请求参数应该是name1=value1&name2=value2的形式。*@return所代表远程资源的响应结果*/publicstaticStringsendPost(Stringurl,Stringparam){PrintWriterout=null;BufferedReaderin=null;Stringresult=;try{URLrealUrl=newURL(url);//打开和URL之间的连接URLConnectionconn=realUrl.openConnection();//设置通用的请求属性conn.setRequestProperty(accept,*/*);conn.setRequestProperty(connection,Keep-Alive);conn.setRequestProperty(user-agent,Mozilla/4.0(compatible;MSIE6.0;WindowsNT5.1;SV1));//发送POST请求必须设置如下两行conn.setDoOutput(true);conn.setDoInput(true);//获取URLConnection对象对应的输出流out=newPrintWriter(conn.getOutputStream());//发送请求参数out.print(param);//flush输出流的缓冲out.flush();//定义BufferedReader输入流来读取URL的响应in=newBufferedReader(newInputStreamReader(conn.getInputStream()));Stringline;while((line=in.readLine())!=null){result+=line;}}catch(Exceptione){System.out.println(发送POST请求出现异常!+e);e.printStackTrace();}//使用finally块来关闭输出流、输入流finally{try{if(out!=null){out.close();}if(in!=null){in.close();}}catch(IOExceptionex){ex.printStackTrace();}}returnresult;}}
本文标题:java发送http的get、post请求
链接地址:https://www.777doc.com/doc-869799 .html