访问:
urlMessage="www.baidu.com?a=1&b=2&c=3";
public static String doGet(String urlMessage) throws Exception {
//创建连接
URL url = new URL(urlMessage.toString());
//url.openConnection()实际生成的是一个URLConnection类的子类HttpURLConnection
//故此处最好将其转化为HttpURLConnection类型的对象
//以便使用HttpURLConnection更多的API
HttpURLConnection urlConnection = null;
urlConnection = (HttpURLConnection) url.openConnection(); //打开连接
//设置是否向httpUrlConnection输出,
//设置是否从httpUrlConnection读入,此外发送post请求必须设置这两个
//最常用的Http请求无非是get和post,
//get请求可以获取静态页面,也可以把参数放在URL字串后面,传递给servlet,
//post与get的 不同之处在于post的参数不是放在URL字串里面,而是放在http请求的正文内。
urlConnection.setDoOutput(true);
urlConnection.setDoInput(true);
urlConnection.setRequestMethod("GET");//GET和POST必须全大写
// 设置连接超时时间
urlConnection.setConnectTimeout(10000);
//设置从主机读取数据超时
urlConnection.setReadTimeout(30000);
//接收类型
urlConnection.setRequestProperty("Accept", "application/json,application/xml, text/html");
// 在http早期,每个http请求都要求打开一个tpc socket连接,并且使用一次之后就断开这个tcp连接。
// 使用keep-alive可以改善这种状态,即在一次TCP连接中可以持续发送多份数据而不会断开连接。
// 以此提高性能和提高httpd服务器的吞吐率
//(更少的tcp连接意味着更少的系统内核调用,socket的accept()和close()调用)。
//但是,长时间的tcp连接容易导致系统资源无效占用。
//所以,正确地设置keep-alive timeout时间非常重要。
// 这个keepalive_timout时间值意味着:一个http产生的tcp连接在传送完最后一个响应后,
//还需要hold住keepalive_timeout秒后,才开始关闭这个连接。
//当httpd守护进程发送完一个响应后,理应马上主动关闭相应的tcp连接,
//设置 keepalive_timeout后,httpd守护进程会想说:”再等等吧,看看浏览器还有没有请求过来”,
//这一等,便是keepalive_timeout时间。
//设置维持长连接:
urlConnection.setRequestProperty("Connection", "Keep-Alive");
//设置文件类型
urlConnection.setRequestProperty("Content-type", "text/html;charset=UTF-8");
//浏览器信息
urlConnection.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1)");
// 连接,从url.openConnection()至此的配置必须要在connect之前完成
urlConnection.connect();
String result = "";
BufferedReader in = null;
//缓存字符输入流,先将字符读到缓存里面,在从缓存中把数据读取出来
in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(), "UTF-8"));
String line = null;
//readLine()只有在数据流发生异常或者另一端被close()掉时,才会返回null值
while ((line = in.readLine()) != null) {
result += line;
}
return result;
}
接收:
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
PrintWriter out = response.getWriter();
System.out.println("请求参数:" + JSON.toJSONString(request.getParameterMap()));
String a= request.getParameter("a");
String b= request.getParameter("b");
String c= request.getParameter("c");
out.print("OK");
out.flush();
out.close();
return;
}