16.POST、GET请求

 

1.1.  发送GET请求

Ÿ   拼接路径和参数,通过URL进行封装,打开一个HttpURLConnection,发送请求

Ÿ   如果参数是中文会出现乱码

Ÿ   URL中包含的中文参数需要使用URLEncoder进行编码

Ÿ   服务器端如果是TOMCAT,其默认使用ISO8859-1编码,接收时需要处理编码问题

1.2.  发送POST请求

Ÿ   通过URL打开一个HttpURLConnection

Ÿ   头信息中除了超时时间和请求方式之外还必须设置Content-Type和Content-Length

Ÿ   从HttpURLConnection获得输出流输出参数数据

Ÿ   服务端可以使用request对象的setCharacterEncoding方法设置编码

 

HOST 写错。则返回 404

由于粗心,在写发送Post请求时,将 

conn.setDoOutput(true); 
写成了
conn.setDoInput(true);
 
 
导致异常
  03-09 13:36:55.666: W/System.err(430): java.net.ProtocolException: Does not support output
 
 
细心,也是程序员重要品质之一啊。认真对待每一个错误。细心、专注,才是王道
复制代码

public class LoginService {

    public static boolean loginByGet(String name, String password) throws Exception {
        name = URLEncoder.encode(name);        // URL 编码
        password = URLEncoder.encode(password);
        
        URL url = new URL("http://192.168.1.111:8080/Login/LoginServlet?name=" + name + "&password=" + password);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setReadTimeout(5000);

        return conn.getResponseCode() == 200;        // 只有获取返回码时,才会真正向服务器发送请求

    }

    public static boolean loginByPost(String name, String password) throws Exception {

        name = URLEncoder.encode(name);
        password = URLEncoder.encode(password);
        
        String data = "name=" + name +"&password=" + password;
        URL url = new URL("http://192.168.1.111:8080/Login/LoginServlet");
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setConnectTimeout(5000);
        
        conn.setRequestMethod("POST");
        // Content-Type    application/x-www-form-urlencoded
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");    // 数据类型
        // Content-Length    41
        conn.setRequestProperty("Content-Length", data.getBytes().length + "");    // 数据长度
        // Host    192.168.1.111:8080
        conn.setRequestProperty("Host", "192.168.1.111:8080");    //设置主机地址
        
        conn.setDoOutput(true);    // 准备写出数据
        conn.getOutputStream().write(data.getBytes());    // 写出数据

        return conn.getResponseCode() == 200;
    }

}
复制代码

 

在服务器端,通过 过滤器、动态代理 完成 Get 请求中,URL的编码

复制代码
public class EncodingFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        final HttpServletRequest req = (HttpServletRequest) request;

        if ("GET".equals(req.getMethod())) {
            // 动态代理
            request = (ServletRequest) Proxy.newProxyInstance(EncodingFilter.class.getClassLoader(), new Class[] { HttpServletRequest.class }, new InvocationHandler() {
                public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                    if (method.getName().equals("getParameter")) {
                        String result = (String) method.invoke(req, args);
                        return result == null ? null : new String(result.getBytes("ISO8859-1"), "UTF-8");
                    }
                    return method.invoke(req, args);
                }
            });
        } else {
            req.setCharacterEncoding("UTF-8"); // 解决 POST 乱码
        }
        chain.doFilter(request, response);
    }

    @Override
    public void destroy() {

    }

}
复制代码
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值