用java代码发送http请求


 1 //发送post请求
 2             PrintWriter out = null;  3             BufferedReader in = null;  4             String result = "";  5             try {  6                 URL realUrl = new URL("http:...........................");  7                 // 打开和URL之间的连接
 8                 URLConnection conn = realUrl.openConnection();  9                 // 设置通用的请求属性
10                 conn.setRequestProperty("accept", "*/*"); 11                 conn.setRequestProperty("connection", "Keep-Alive"); 12                 conn.setRequestProperty("user-agent", 13                         "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)"); 14                 // 发送POST请求必须设置如下两行
15                 conn.setDoOutput(true); 16                 conn.setDoInput(true); 17                 // 获取URLConnection对象对应的输出流
18                 out = new PrintWriter(conn.getOutputStream()); 19                 // 发送请求参数 20                //参数格式如下
21                 out.print("uid="+uid+"&status="+status+"&gender="+gender+"&channel="+u.getChannel()); 22                 // flush输出流的缓冲
23  out.flush(); 24                 // 定义BufferedReader输入流来读取URL的响应
25                 in = new BufferedReader( 26                         new InputStreamReader(conn.getInputStream(),"UTF-8")); 27                 String line = ""; 28                 while ((line = in.readLine()) != null) { 29                     result += line; 30  } 31 
32             } catch (Exception e) { 33                 System.out.println("发送 POST 请求出现异常!"+e); 34  e.printStackTrace(); 35  } 36             //使用finally块来关闭输出流、输入流
37             finally{ 38                 try{ 39                     if(out!=null){ 40  out.close(); 41  } 42                     if(in!=null){ 43  in.close(); 44  } 45  } 46                 catch(IOException ex){ 47  ex.printStackTrace(); 48  } 49  } 50             System.out.println(result);

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM