Java-->服务器的响应(Servlet--doGet&doPost)

--> Servelet: 用于接收请求(客户端,浏览器),做出响应的,服务器端的,java类

--> ServletLogin -- Web项目服务器响应的Java实现

package com.dragon.java.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class ServletLogin
 */
@WebServlet("/ServletLogin")
public class ServletLogin extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String user = parse(request.getParameter("user"));
        String pwd = parse(request.getParameter("pwd"));
        System.out.println(user + ":" + pwd);

        response.setContentType("text/html;charset=utf-8");
        PrintWriter writer = response.getWriter();
        writer.println(user + "登陆成功!");
        // 服务器会自动关流
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("utf-8"); // 只解决post 请求乱码问题
        doGet(request, response);
    }

    public String parse(String msg) throws UnsupportedEncodingException {
        return new String(msg.getBytes("iso8859-1"), "utf-8");
    }
}

1、doGet 方法:

--> HttpURLConnectionUtil 工具类

package com.dragon.java.urlbyget;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class HttpURLConnectionUtil {
    public static InputStream getInputStreamByGet(String url) {
        try {
            HttpURLConnection conn = (HttpURLConnection) new URL(url)
                    .openConnection();
            conn.setRequestMethod("GET");
            conn.setReadTimeout(10000);
            conn.setConnectTimeout(10000);
            // 用这个方法可以设置http的请求头
            // conn.addRequestProperty("Accept", "......");

            if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
                // 获取编码
                // String contentType = conn.getContentType();
                // String string = contentType.split("=")[1];

                InputStream inputStream = conn.getInputStream();
                return inputStream;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}

--> Test 测试类

package com.dragon.java.urlbyget;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

public class Test {
    public static void main(String[] args) {
        InputStream inputStreamByGet = HttpURLConnectionUtil
                .getInputStreamByGet("http://www.baidu.com");
        try {
            BufferedReader br = new BufferedReader(new InputStreamReader(
                    inputStreamByGet, "gb2312"));
            String line = "";
            while ((line = br.readLine()) != null) {
                System.out.println(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

----------------------------------邪恶的分割线------------------------------------

2、doPost 方法

--> HttpURLConnectionUtil 工具类

package com.dragon.java.urlbypost;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class HttpURLConnectionUtil {
    private static String charset;

    public static InputStream getInputStreamByPost(String url, String parms) {
        try {
            HttpURLConnection conn = (HttpURLConnection) new URL(url)
                    .openConnection();
            conn.setReadTimeout(5000);
            conn.setConnectTimeout(5000);
            conn.setRequestMethod("POST");

            conn.setDoOutput(true);
            OutputStream outputStream = conn.getOutputStream();
            outputStream.write(parms.getBytes());
            if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
                String contentType = conn.getContentType();
                charset = contentType.split("=")[1];

                InputStream inputStream = conn.getInputStream();
                return inputStream;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String getCharset() {
        return charset;
    }
}

--> InputStreamUtil 流到String的转换类

package com.dragon.java.urlbypost;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

public class InputStreamUtil {

    public static String inputStreamToString(InputStream is, String charset) {
        StringBuffer sb = new StringBuffer();
        try (BufferedReader br = new BufferedReader(new InputStreamReader(is,
                charset));) {
            char[] buffer = new char[1024];
            int len = -1;
            while ((len = br.read(buffer)) != -1) {
                sb.append(buffer, 0, len);
            }
            return sb.toString();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}

--> Test 测试类

package com.dragon.java.urlbypost;

import java.io.InputStream;

public class Test {
    public static void main(String args[]) {

    // 需要对URL中的中文参数进行编码。
    String user = URLEncoder.encode("张三", "utf-8");
    String pwd = URLEncoder.encode("你好", "utf-8");
    InputStream inputStreamByPost = HttpURLConnectionUtil
        .getInputStreamByPost(
            "http://192.168.2.11:8080/08-23/ServletLogin", "user="
                + user + "&pwd=" + pwd);

        System.out.println(InputStreamUtil.inputStreamToString(
                inputStreamByPost, HttpURLConnectionUtil.getCharset()));
    }
}

---> 注意先将Web项目导入到服务器并运行...

posted on 2016-08-23 13:56  西门吃雪  阅读(3395)  评论(0编辑  收藏  举报

导航