httpclientservlet.java

来自「JAVA Servlet2.3外文书籍源码」· Java 代码 · 共 71 行

JAVA
71
字号
import java.io.*;
import java.net.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class HttpClientServlet extends HttpServlet {
	public void doPost (HttpServletRequest request,
                      HttpServletResponse response) 
      throws ServletException, IOException{
    PrintWriter out = response.getWriter();
    String[] content = getContent();
    out.println("<html>");
    out.println("<head>");
    out.println("</head>");
    out.println("<body>");
    for( int i = 0; i < content.length; i++ ) {
      out.println(content[i]);
    }
    out.println("</body>");
    out.println("</html>");
    out.close();
  }

  private String getURLContent( String urlString, String country ) 
      throws Exception {
    URL url = new URL( urlString );
    URLConnection connection = url.openConnection();
    connection.setDoOutput(true);
    PrintWriter out = new PrintWriter(connection.getOutputStream());
    out.println("country=" + country);
    out.close();

    BufferedReader in = new BufferedReader(new InputStreamReader(
                                    connection.getInputStream()));

    StringBuffer sb = new StringBuffer( 1024 );
    
    String inputLine;
    while ((inputLine = in.readLine()) != null) {
        sb.append( inputLine );
    }
    in.close();
    return sb.toString();
  }

  String[] getContent()
  {
    String[] countries = { "JP", "UK", "MX" };
    String[] content = new String[countries.length];
    try{
      for( int i = 0; i < countries.length; i++ ){
        content[i] = "I asked for " + countries[i] + " and I got <b>(" +
                     getURLContent("http://localhost:8080/webservice/servlet/HttpService",
                      countries[i]) + 
                     ")</b><br>";
      }
    } catch(Exception e)
    {
      content = new String[1];
      content[0] = e.getMessage();  
    }
    return content;
  }

  public void doGet (HttpServletRequest request,
                     HttpServletResponse response)
      throws ServletException, IOException{
    doPost( request, response );
  }
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?