本文参考:
http://blog.sina.com.cn/s/blog_9ed7f0d70101i8op.html
http://www.cnblogs.com/cnryb/archive/2013/06/27/3158027.html
HttpClient httpClient = new HttpClient(); //打开窗口 PostMethod getMethod = new PostMethod("http://localhost:8080/webapp/"); //输入网址 try { int statusCode = httpClient.executeMethod(getMethod); //按下回车运行,得到返回码 System.out.println(statusCode); if (statusCode != HttpStatus.SC_OK) { System.err.println("Method failed: " + getMethod.getStatusLine()); } //读取内容 byte[] responseBody = getMethod.getResponseBody(); //得到返回的内容 //处理内容 System.out.println(new String(responseBody)); } catch (Exception e) { e.printStackTrace(); } finally { getMethod.releaseConnection(); }
下面代码模仿服务器,通过代码,构建"http://localhost:8080/webapp/"的服务器,接收内容,executeMethod 会调用handle方法
package com.cnryb; import java.io.IOException; import java.io.OutputStream; import java.net.InetSocketAddress; import org.apache.http.HttpStatus; import com.sun.net.httpserver.*; public class HttpSer { /** * @param args * @throws IOException */ public static void main(String[] args) throws IOException { // HttpServer server = HttpServer.create(new InetSocketAddress( // "127.0.0.1", 8765), 0); // server.createContext("/",new MyResponseHandler()); // server.setExecutor(null); // creates a default executor // server.start(); [align=center] ExecutorService executor = Executors.newFixedThreadPool(20); int port = Integer.parseInt(prop.getProperty("service_port"));// 8080 HttpServer server = HttpServer.create(new InetSocketAddress(port), 0); String url = prop.getProperty("service_url");//wapp HttpContext context = server.createContext(url, new MyResponseHandler ()); context.getFilters().add(new ParameterFilter()); server.setExecutor(executor); server.start();[/align] } public static class MyResponseHandler implements HttpHandler { @Override public void handle(HttpExchange httpExchange) throws IOException { // 可以获取相应的内容 以下自己追加 Map<String, Object> params = (Map<String, Object>)httpExchange.getAttribute("parameters"); if (params.get("xml") != null) { resquestBody = params.get("xml").toString(); } else if (params.get("text/xml") != null) { resquestBody = params.get("text/xml").toString(); } else if (params.get("OriginRequestBody") != null) { resquestBody = params.get("OriginRequestBody").toString(); } // ------------------------------------- //针对请求的处理部分 //返回请求响应时,遵循HTTP协议 String responseString = "<font color='#ff0000'>Hello! This a HttpServer!</font>"; //设置响应头 httpExchange.sendResponseHeaders(HttpStatus.SC_OK, responseString.length()); OutputStream os = httpExchange.getResponseBody(); os.write(responseString.getBytes()); os.close(); } } }