天天看点

Java笔记7:最简单的网络请求Demo

一、服务器端

1 新建一个工程,建立一个名为MyRequest的工程。

2 FileàProject StructureàModulesà点击最右侧的“+”àLibraryàJava

找到Tomcat中的lib目录下的servlet-api.jar,添加进来

Java笔记7:最简单的网络请求Demo
Java笔记7:最简单的网络请求Demo

3 建立LoginServlet类,内容如下

[java] view plain copy

import java.io.IOException;  

import javax.servlet.ServletException;  

import javax.servlet.http.HttpServlet;  

import javax.servlet.http.HttpServletRequest;  

import javax.servlet.http.HttpServletResponse;  

public class LoginServlet extends HttpServlet {  

    private static final long serialVersionUID = 1L;  

    public LoginServlet() {  

        super();  

    }  

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {  

        this.doPost(request, response);  

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {  

        String username = request.getParameter("username");  

        String blog = request.getParameter("blog");  

        System.out.println(username);  

        System.out.println(blog);  

        response.setContentType("text/plain; charset=UTF-8");  

        response.setCharacterEncoding("UTF-8");  

        response.getWriter().write("It is ok!");  

}  

4 编译LoginServlet.java,得到LoginServlet.class

Java笔记7:最简单的网络请求Demo

5 在Tomcat中的webapps中添加MyHttpServer\WEB-INF\classes,并把上一步生成的LoginServlet.class拷进来

Java笔记7:最简单的网络请求Demo

6 在WEB-INF目录下建立web.xml文件,内容如下:

[html] view plain copy

<?xml version="1.0" encoding="UTF-8"?>  

<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">  

  <display-name>OneHttpServer</display-name>  

  <welcome-file-list>  

    <welcome-file>LoginServlet</welcome-file>  

  </welcome-file-list>  

  <servlet>  

    <description></description>  

    <display-name>LoginServlet</display-name>  

    <servlet-name>LoginServlet</servlet-name>  

    <servlet-class>LoginServlet</servlet-class>  

  </servlet>  

  <servlet-mapping>  

    <url-pattern>/LoginServlet</url-pattern>  

  </servlet-mapping>  

</web-app>  

Java笔记7:最简单的网络请求Demo

7 执行Tomcat下的bin目录下的startup.bat来启动Tomcat

8 在浏览器中输入http://localhost:8080/MyHttpServer,若见到页面显示“It is ok!”则表示服务器端配置成功。

Java笔记7:最简单的网络请求Demo

二、客户端

1 Get请求

在MyRequest工程新建HttpGetRequest类,内容如下:

import java.io.BufferedReader;  

import java.io.InputStream;  

import java.io.InputStreamReader;  

import java.net.HttpURLConnection;  

import java.net.URL;  

import java.net.URLConnection;  

public class HttpGetRequest {  

    /** 

     * Main 

     * @param args 

     * @throws Exception 

     */  

    public static void main(String[] args) throws Exception {  

        System.out.println(doGet());  

     * Get Request 

     * @return 

    public static String doGet() throws Exception {  

        URL localURL = new URL("http://localhost:8080/MyHttpServer/");  

        URLConnection connection = localURL.openConnection();  

        HttpURLConnection httpURLConnection = (HttpURLConnection)connection;  

        httpURLConnection.setRequestProperty("Accept-Charset", "utf-8");  

        httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");  

        InputStream inputStream = null;  

        InputStreamReader inputStreamReader = null;  

        BufferedReader reader = null;  

        StringBuffer resultBuffer = new StringBuffer();  

        String tempLine = null;  

        if (httpURLConnection.getResponseCode() >= 300) {  

            throw new Exception("HTTP Request is not success, Response code is " + httpURLConnection.getResponseCode());  

        }  

        try {  

            inputStream = httpURLConnection.getInputStream();  

            inputStreamReader = new InputStreamReader(inputStream);  

            reader = new BufferedReader(inputStreamReader);  

            while ((tempLine = reader.readLine()) != null) {  

                resultBuffer.append(tempLine);  

            }  

        } finally {  

            if (reader != null) {  

                reader.close();  

            if (inputStreamReader != null) {  

                inputStreamReader.close();  

            if (inputStream != null) {  

                inputStream.close();  

        return resultBuffer.toString();  

运行结果:

It is ok!

2 Post请求

新建HttpPostRequest.java类,内容如下:

import java.io.OutputStream;  

import java.io.OutputStreamWriter;  

public class HttpPostRequest {  

        System.out.println(doPost());  

     * Post Request 

    public static String doPost() throws Exception {  

        String parameterData = "username=nickhuang&blog=http://www.cnblogs.com/nick-huang/";  

        httpURLConnection.setDoOutput(true);  

        httpURLConnection.setRequestMethod("POST");  

        httpURLConnection.setRequestProperty("Content-Length", String.valueOf(parameterData.length()));  

        OutputStream outputStream = null;  

        OutputStreamWriter outputStreamWriter = null;  

            outputStream = httpURLConnection.getOutputStream();  

            outputStreamWriter = new OutputStreamWriter(outputStream);  

            outputStreamWriter.write(parameterData.toString());  

            outputStreamWriter.flush();  

            if (httpURLConnection.getResponseCode() >= 300) {  

                throw new Exception("HTTP Request is not success, Response code is " + httpURLConnection.getResponseCode());  

            if (outputStreamWriter != null) {  

                outputStreamWriter.close();  

            if (outputStream != null) {  

                outputStream.close();  

3 对Get和Post进行封装

封装类:

import java.net.InetSocketAddress;  

import java.net.Proxy;  

import java.util.Iterator;  

import java.util.Map;  

public class HttpRequestor {  

    private String charset = "utf-8";  

    private Integer connectTimeout = null;  

    private Integer socketTimeout = null;  

    private String proxyHost = null;  

    private Integer proxyPort = null;  

     * Do GET request 

     * @param url 

     * @throws IOException 

    public String doGet(String url) throws Exception {  

        URL localURL = new URL(url);  

        URLConnection connection = openConnection(localURL);  

        httpURLConnection.setRequestProperty("Accept-Charset", charset);  

     * Do POST request 

     * @param parameterMap 

    public String doPost(String url, Map parameterMap) throws Exception {  

        /* Translate parameter map to parameter date string */  

        StringBuffer parameterBuffer = new StringBuffer();  

        if (parameterMap != null) {  

            Iterator iterator = parameterMap.keySet().iterator();  

            String key = null;  

            String value = null;  

            while (iterator.hasNext()) {  

                key = (String)iterator.next();  

                if (parameterMap.get(key) != null) {  

                    value = (String)parameterMap.get(key);  

                } else {  

                    value = "";  

                }  

                parameterBuffer.append(key).append("=").append(value);  

                if (iterator.hasNext()) {  

                    parameterBuffer.append("&");  

        System.out.println("POST parameter : " + parameterBuffer.toString());  

        httpURLConnection.setRequestProperty("Content-Length", String.valueOf(parameterBuffer.length()));  

            outputStreamWriter.write(parameterBuffer.toString());  

    private URLConnection openConnection(URL localURL) throws IOException {  

        URLConnection connection;  

        if (proxyHost != null && proxyPort != null) {  

            Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHost, proxyPort));  

            connection = localURL.openConnection(proxy);  

        } else {  

            connection = localURL.openConnection();  

        return connection;  

     * Render request according setting 

     * @param request 

    private void renderRequest(URLConnection connection) {  

        if (connectTimeout != null) {  

            connection.setConnectTimeout(connectTimeout);  

        if (socketTimeout != null) {  

            connection.setReadTimeout(socketTimeout);  

    /* 

     * Getter & Setter 

    public Integer getConnectTimeout() {  

        return connectTimeout;  

    public void setConnectTimeout(Integer connectTimeout) {  

        this.connectTimeout = connectTimeout;  

    public Integer getSocketTimeout() {  

        return socketTimeout;  

    public void setSocketTimeout(Integer socketTimeout) {  

        this.socketTimeout = socketTimeout;  

    public String getProxyHost() {  

        return proxyHost;  

    public void setProxyHost(String proxyHost) {  

        this.proxyHost = proxyHost;  

    public Integer getProxyPort() {  

        return proxyPort;  

    public void setProxyPort(Integer proxyPort) {  

        this.proxyPort = proxyPort;  

    public String getCharset() {  

        return charset;  

    public void setCharset(String charset) {  

        this.charset = charset;  

客户端测试代码:

import java.util.HashMap;  

public class Call {  

        /* Post Request */  

        Map dataMap = new HashMap();  

        dataMap.put("username", "Zheng");  

        dataMap.put("blog", "IT");  

        System.out.println(new HttpRequestor().doPost("http://localhost:8080/MyHttpServer/", dataMap));  

        /* Get Request */  

        System.out.println(new HttpRequestor().doGet("http://localhost:8080/MyHttpServer/"));  

POST parameter : blog=IT&username=Zheng

学习时的痛苦是暂时的 未学到的痛苦是终生的