码迷,mamicode.com
首页 > Web开发 > 详细

向Web站点发送GET请求,POST请求,并从Web站点取得相应数据示例

时间:2015-05-31 00:07:35      阅读:216      评论:0      收藏:0      [点我收藏+]

标签:urlconnection   url   sendget   sendpost   


package cn.internet.demo;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.Map;

public class GetPostTest {

	/**
	 * 向指定URL发送GET方式请求
	 */
	public static String sendGet(String url,String param){
		String result = "";
		String urlName = url+"?"+param;
		try {
			URL realUrl = new URL(urlName);
			// 打开联接
			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)");
			
			// 建立实际的联接
			conn.connect();			
			
			System.out.println("文件大小:"+conn.getContentLength());
			// 获取所有的相应头字段
			Map<String, List<String>> map = conn.getHeaderFields();
			// 遍历所有的相应头字段
			for (String key:map.keySet()) {
				System.out.println(key+"--->"+map.get(key));
			}
			
			// 定义 BufferedReader输入流来读取URL的相应
			try(BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(),"utf-8"))){
				String line;
				while ((line = in.readLine())!=null) {
					result += "\n"+line;
				}
			}
		} catch (Exception e) {
			System.out.println("发送Get请求出现异常!");
			e.printStackTrace();
		}
		return result;
	}
	
	public static String sendPost(String url,String param){
		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);
			
			// 获取URLConnection对象对应的输出流
			try(PrintWriter out = new PrintWriter(conn.getOutputStream())){
				out.print(param);	// 发送请求参数
				out.flush();		// flush输出流的缓冲
			}
			// 定义 BufferedReader输入流来读取URL的相应
			try(BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(),"utf-8"))){
				String line;
				while ((line = in.readLine())!=null) {
					result += "\n"+line;
				}
			}
			
			// 获取所有的相应头字段
			Map<String, List<String>> map = conn.getHeaderFields();
			// 遍历所有的相应头字段
			for (String key:map.keySet()) {
				System.out.println(key+"--->"+map.get(key));
			}
		
		} catch (Exception e) {
			System.out.println("发送Get请求出现异常!");
			e.printStackTrace();
		}
		return result;
	}
	
	public static void main(String[] args) {
//		String s = GetPostTest.sendGet("http://localhost:8080/NetWork_Code/index.jsp", "name=rapido&pwd=liying5201314");
//		System.out.println("get: "+s);
		
		String s = GetPostTest.sendGet("http://localhost:8080/NetWork_Code/data.json", null);
		System.out.println("get: "+s);
		
//		String s2 = GetPostTest.sendPost("http://localhost:8080/NetWork_Code/index.jsp", "name=rapido&pwd=liying5201314");
//		System.out.println("post: "+s2);
	}
}
在Web应用程序中测试一个index.jsp页面联接

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
	String name = request.getParameter("name");
	String pwd = request.getParameter("pwd");

	System.out.println("name:" + name + ",pwd:" + pwd);
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>My JSP 'index.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
</head>
<body>
	This is my JSP page.
	<h1 style="color:red">用户名:<%=name %>, 密码:<%=pwd %></h1>
	<br>
</body>
</html>
启动服务后,执行main方法返回以下类型数据
文件大小:539
null--->[HTTP/1.1 200 OK]
Date--->[Sat, 30 May 2015 14:57:58 GMT]
Content-Length--->[539]
Set-Cookie--->[JSESSIONID=CD19ECBE035FDC1287CE22AD5CEF6DBA; Path=/NetWork_Code/; HttpOnly]
Content-Type--->[text/html;charset=UTF-8]
Server--->[Apache-Coyote/1.1]
get: 


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>My JSP 'index.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
</head>
<body>
	This is my JSP page.
	<h1 style="color:red">用户名:rapido, 密码:liying5201314</h1>
	<br>
</body>
</html>


向Web站点发送GET请求,POST请求,并从Web站点取得相应数据示例

标签:urlconnection   url   sendget   sendpost   

原文地址:http://blog.csdn.net/xiaokui_wingfly/article/details/46278895

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!