一,简介
经常看见大家用HttpClient发送http请求,其实Java也自带了相关类库,本篇简单做个介绍,主要是给个示例。
另外,关于编码的部分尤其需要注意,编码的原理较为复杂,就不再具体解释了。
二,环境搭建
首先搭建一个Java Web项目JavaNetDemo,并写一个Servlet用于接受Http请求并返回结果用于测试,代码如下:
package http;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* 用来测试是否调用到了LoginServlet
* @author 猫哥
* @date 2017.4.27
*/
@WebServlet(urlPatterns="/LoginServlet")
public class LoginServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setCharacterEncoding("UTF-8");
request.setCharacterEncoding("UTF-8");
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
out.println("<HTML>");
out.println(" <HEAD><TITLE>A Servlet</TITLE></HEAD>");
out.println(" <BODY>");
out.println("doGet方法调用了");
String name=request.getParameter("name");
out.println("name:"+this.parseGet(name));
String password=request.getParameter("password");
out.println("password:"+this.parseGet(password));
out.println(" </BODY>");
out.println("</HTML>");
out.flush();
out.close();
}
/**
*
* @param input
* @return
* @throws UnsupportedEncodingException
*/
private String parseGet(String input) throws UnsupportedEncodingException{
input = URLEncoder.encode(input, "iso8859-1");
input=URLDecoder.decode(input, "utf-8");
return input;
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setCharacterEncoding("UTF-8");
request.setCharacterEncoding("UTF-8");
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
out.println("<HTML>");
out.println(" <HEAD><TITLE>A Servlet</TITLE></HEAD>");
out.println(" <BODY>");
out.println("doPost方法调用了");
String name=request.getParameter("name");
out.println("name:"+name);
String password=request.getParameter("password");
out.println("name:"+password);
out.println(" </BODY>");
out.println("</HTML>");
out.flush();
out.close();
}
}
三,Http请求类
注意该类的两个静态方法分别给出了通过代码发送http GET和POST请求的具体例子,发送请求时的参数封装为QueryParams类用于保存参数。
package http;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLConnection;
/**
* Http请求发起类
* @author 猫哥
* @date 2017.4.27
*/
public class HttpSender {
/**
* 测试入口
* @throws UnsupportedEncodingException
*/
public static void main(String[] args) throws UnsupportedEncodingException{
String getResult=HttpSender.sendPostRequest();
System.out.println(getResult);
}
/**
* 发起http GET请求
* @return 请求的返回值
*/
public static String sendGetRequest(){
StringBuilder sb=new StringBuilder();
QueryParams suffix=new QueryParams();
suffix.add("name", "猫哥");
suffix.add("password","1234");
try {
URL url=new URL("http://127.0.0.1:8080/JavaNetDemo/LoginServlet?x=0"+suffix.toString());
InputStream in=new BufferedInputStream(url.openStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(in,"UTF-8"));
String line;
while((line=reader.readLine())!=null){
sb.append(line);
}
} catch (Exception e) {
e.printStackTrace();
}
return sb.toString();
}
public static String sendPostRequest(){
StringBuilder sb=new StringBuilder();
QueryParams suffix=new QueryParams();
suffix.add("name", "猫哥");
suffix.add("password","1234");
try {
//打开post通道
URL url=new URL("http://127.0.0.1:8080/JavaNetDemo/LoginServlet");
URLConnection urlCon=url.openConnection();
urlCon.setDoOutput(true);
//写参数
OutputStreamWriter out=new OutputStreamWriter(urlCon.getOutputStream(),"UTF-8");
out.write(suffix.toString());
out.flush();
out.close();
//读返回
BufferedReader reader = new BufferedReader(new InputStreamReader(urlCon.getInputStream(),"UTF-8"));
String line;
while((line=reader.readLine())!=null){
sb.append(line);
}
} catch (Exception e) {
e.printStackTrace();
System.out.println(e.getMessage());
}
return sb.toString();
}
}
四,QueryParams参数类
package http;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
/**
* 参数封装
* @author 猫哥
* @date 2017.4.27
*/
public class QueryParams {
/**
* 内容
*/
private StringBuilder suffix=new StringBuilder();
/**
* 编码
*/
private String code;
public QueryParams(){
this.code="UTF-8";
}
public QueryParams(String code){
this.code=code;
}
public void add(String name,String value){
suffix.append("&");
try {
suffix.append(URLEncoder.encode(name,code));
suffix.append("=");
suffix.append(URLEncoder.encode(value,code));
} catch (UnsupportedEncodingException e) {
//记录下日志
}
}
@Override
public String toString(){
return suffix.toString();
}
}
Over!