欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

java应用程序向服务器发送request请求,并接受响应

程序员文章站 2022-07-16 14:16:28
...

下面代码是别人写的,经测试很好用

//get形式发生请求

public static String sendGet(String url,String param){
  String result = "";
  BufferedReader in = null;
  try{
   String urlNameString = url+"?"+param;
   URL realUrl = new URL(urlNameString);
   //发送请求
   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();
   for(String key:map.keySet()){
    System.out.println(key+"="+map.get(key));
   }
   in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
   String line = null;
   while((line = in.readLine()) != null){
    result +=line;
   }
  }catch(Exception e){
   System.out.println("发送get请求出现错误!"+e);
   e.printStackTrace();
  }
  finally{
   try {
    if(in != null){
     in.close();
    }
   } catch (Exception e2) {
    // TODO: handle exception
    e2.printStackTrace();
   }
  }
  return result;
 }

//post发送

public static String sendPost(String url,String param){
  PrintWriter out = null;
  BufferedReader in = null;
  String result = "";
  try{
   URL realUrl = new 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);
   out = new PrintWriter(conn.getOutputStream());
   out.println(param);
   out.flush();
   //conn.getInputStream()这句话会真正的发出请求
   in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
   String line = null;
   while((line = in.readLine()) != null){
    result +=line;
   }
  }catch(Exception e){
   System.out.println("发送POST请求出错!");
   e.printStackTrace();
  }
  finally{
   try{
    if(out != null)
     out.close();
    if(in != null)
     in.close();
   }catch(IOException ex){
    ex.printStackTrace();
   }
  }
  return result;
 }