分为二类,GET与POST请求。二者的区别在于:
a:) get请求可以获取静态页面,也可以把参数放在URL字串后面,传递给servlet,
b:) post与get的不同之处在于post的参数不是放在URL字串里面,而是放在http请求的正文内。
下面贴出一个jsp+servlet的小例子供大家参考:
package com.http.test;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class TestHttp {
public static String sendGet(String url,String param){
String result = "";
BufferedReader in = null;
String urlNameString = url + "?" + param;
try {
URL realUrl = new URL(urlNameString);
HttpURLConnection httpConn = (HttpURLConnection) realUrl.openConnection();
// 设置通用的请求属性
httpConn.setRequestProperty("Content-Type", "text/xml;charset=GBK");
httpConn.setRequestProperty("accept", "*/*");
httpConn.setRequestProperty("connection", "Keep-Alive");
httpConn.setRequestProperty("user-agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
//建立实际的连接
httpConn.connect();
//定义 BufferedReader输入流来读取URL的响应
in = new BufferedReader(new InputStreamReader(httpConn.getInputStream()));
String line;
while((line = in.readLine()) != null){
result += line;
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
if(in != null){
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return result;
}
public static String sendPost(String url,String param){
String result = "";
BufferedReader in = null;
PrintWriter out = null;
try {
URL realUrl = new URL(url);
HttpURLConnection httpConn = (HttpURLConnection) realUrl.openConnection();
//发送post请求必须设置这两行
httpConn.setDoInput(true);
httpConn.setDoOutput(true);
//获取URLConnection对象对应的输出流
out = new PrintWriter(httpConn.getOutputStream());
out.print(param);
out.flush();
// 设置通用的请求属性
//定义 BufferedReader输入流来读取URL的响应
in = new BufferedReader(new InputStreamReader(httpConn.getInputStream()));
String line;
while((line = in.readLine()) != null){
result += line;
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
if(in != null){
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(out != null){
out.close();
}
}
return result;
}
public static void main(String[] args) {
//测试get请求
//String s = TestHttp.sendGet("http://localhost:8080/HttpSend/HttpServlet", "name=jbit&pwd=123");
//System.out.println(s);
String ss = TestHttp.sendPost("http://localhost:8080/HttpSend/HttpPostServlet", "name=jbit&pwd=123");
System.out.println(ss);
}
}
//servlet就不贴出来了,相信大家都能轻松写出来!