Skip to content

Commit 6e25ece

Browse files
committed
重构:将请求和响应的处理抽成独立的类和方法,使之可以复用;server相关的类移至一个独立的目录
1 parent a6c055b commit 6e25ece

5 files changed

Lines changed: 246 additions & 91 deletions

File tree

Lines changed: 85 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,85 @@
1+
/**
2+
* 创建时间:2016-2-23
3+
*/
4+
package cn.aofeng.demo.httpclient;
5+
6+
import java.io.IOException;
7+
import java.net.URISyntaxException;
8+
9+
import org.apache.http.Header;
10+
import org.apache.http.HttpEntity;
11+
import org.apache.http.StatusLine;
12+
import org.apache.http.client.ClientProtocolException;
13+
import org.apache.http.client.methods.CloseableHttpResponse;
14+
import org.apache.http.client.methods.HttpGet;
15+
import org.apache.http.client.methods.HttpPost;
16+
import org.apache.http.impl.client.CloseableHttpClient;
17+
import org.apache.http.impl.client.HttpClients;
18+
import org.apache.http.util.EntityUtils;
19+
import org.apache.log4j.Logger;
20+
21+
/**
22+
* HttpClient的基本操作。
23+
*
24+
* @author <a href="mailto:[email protected]">聂勇</a>
25+
*/
26+
public class HttpClientBasic {
27+
28+
private static Logger _logger = Logger.getLogger(HttpClientBasic.class);
29+
30+
private static String _targetHost = "http://127.0.0.1:8888";
31+
32+
private static String _charset = "utf-8";
33+
34+
public void get() throws URISyntaxException, ClientProtocolException, IOException {
35+
CloseableHttpClient client = HttpClients.createDefault();
36+
HttpGet get = new HttpGet(_targetHost+"/get");
37+
CloseableHttpResponse response = client.execute(get);
38+
processResponse(response);
39+
}
40+
41+
private void processResponse(CloseableHttpResponse response)
42+
throws UnsupportedOperationException, IOException {
43+
try {
44+
// 获取响应头
45+
Header[] headers = response.getAllHeaders();
46+
for (Header header : headers) {
47+
_logger.info(header.getName() + ":" + header.getValue());
48+
}
49+
50+
// 获取状态信息
51+
StatusLine sl =response.getStatusLine();
52+
_logger.info( String.format("ProtocolVersion:%s, StatusCode:%d, Desc:%s",
53+
sl.getProtocolVersion().toString(), sl.getStatusCode(), sl.getReasonPhrase()) );
54+
55+
// 获取响应内容
56+
HttpEntity entity = response.getEntity();
57+
_logger.info( String.format("ContentType:%s, Length:%d, Encoding:%s",
58+
null == entity.getContentType() ? "" : entity.getContentType().getValue(),
59+
entity.getContentLength(),
60+
null == entity.getContentEncoding() ? "" : entity.getContentEncoding().getValue()) );
61+
_logger.info(EntityUtils.toString(entity, _charset));
62+
// _logger.info( IOUtils.toString(entity.getContent(), _charset) ); // 大部分情况下效果与上行语句等同,但实现上的编码处理不同
63+
} finally {
64+
response.close();
65+
}
66+
}
67+
68+
public void post() throws ClientProtocolException, IOException {
69+
CloseableHttpClient client = HttpClients.createDefault();
70+
HttpPost post = new HttpPost(_targetHost+"/post");
71+
post.addHeader("Cookie", "character=abcdefghijklmnopqrstuvwxyz; sign=abc-123-jkl-098");
72+
CloseableHttpResponse response = client.execute(post);
73+
processResponse(response);
74+
}
75+
76+
/**
77+
* @param args
78+
*/
79+
public static void main(String[] args) throws Exception {
80+
HttpClientBasic basic = new HttpClientBasic();
81+
basic.get();
82+
basic.post();
83+
}
84+
85+
}

src/cn/aofeng/demo/httpclient/SimpleHttpServer.java

Lines changed: 0 additions & 91 deletions
This file was deleted.
Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
/**
2+
* 创建时间:2016-8-18
3+
*/
4+
package cn.aofeng.demo.httpclient.server;
5+
6+
import java.io.IOException;
7+
import java.io.OutputStream;
8+
import java.io.UnsupportedEncodingException;
9+
import java.net.InetSocketAddress;
10+
import java.net.URI;
11+
import java.util.List;
12+
import java.util.Map.Entry;
13+
import java.util.Set;
14+
15+
import org.apache.commons.io.IOUtils;
16+
import org.apache.log4j.Logger;
17+
18+
import com.sun.net.httpserver.Headers;
19+
import com.sun.net.httpserver.HttpExchange;
20+
import com.sun.net.httpserver.HttpHandler;
21+
22+
/**
23+
* @author <a href="mailto:[email protected]">聂勇</a>
24+
*/
25+
public abstract class AbstractHandler implements HttpHandler {
26+
27+
private static Logger _logger = Logger.getLogger(AbstractHandler.class);
28+
29+
protected String _charset = "utf-8";
30+
31+
public AbstractHandler(String charset) {
32+
this._charset = charset;
33+
}
34+
35+
/**
36+
* 处理请求头。
37+
*/
38+
public void handleHeader(HttpExchange httpEx) {
39+
InetSocketAddress remoteAddress = httpEx.getRemoteAddress();
40+
_logger.info("收到来自"+remoteAddress.getAddress().getHostAddress()+":"+remoteAddress.getPort()+"的请求");
41+
42+
URI rUri = httpEx.getRequestURI();
43+
_logger.info("请求地址:"+rUri.toString());
44+
45+
String method = httpEx.getRequestMethod();
46+
_logger.info("请求方法:"+method);
47+
48+
Headers headers = httpEx.getRequestHeaders();
49+
Set<Entry<String, List<String>>> headerSet = headers.entrySet();
50+
_logger.info("请求头:");
51+
for (Entry<String, List<String>> header : headerSet) {
52+
_logger.info(header.getKey()+":"+header.getValue());
53+
}
54+
}
55+
56+
/**
57+
* 处理响应。
58+
*/
59+
public void handleResponse(HttpExchange httpEx, String content)
60+
throws UnsupportedEncodingException, IOException {
61+
String rc = "冒号后面是收到的请求,原样返回:"+content;
62+
byte[] temp = rc.getBytes(_charset);
63+
Headers outHeaders = httpEx.getResponseHeaders();
64+
outHeaders.set("ABC", "123");
65+
httpEx.sendResponseHeaders(200, temp.length);
66+
OutputStream outs = httpEx.getResponseBody();
67+
outs.write(temp);
68+
IOUtils.closeQuietly(outs);
69+
}
70+
71+
}
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
/**
2+
* 创建时间:2016-8-18
3+
*/
4+
package cn.aofeng.demo.httpclient.server;
5+
6+
import java.io.IOException;
7+
import java.io.InputStream;
8+
import java.io.UnsupportedEncodingException;
9+
import java.net.URLDecoder;
10+
11+
import org.apache.commons.io.IOUtils;
12+
import org.apache.log4j.Logger;
13+
14+
import com.sun.net.httpserver.HttpExchange;
15+
import com.sun.net.httpserver.HttpHandler;
16+
17+
/**
18+
* 字符串处理器。
19+
*
20+
* @author <a href="mailto:[email protected]">聂勇</a>
21+
*/
22+
public class CharacterHandler extends AbstractHandler implements HttpHandler {
23+
24+
static Logger _logger = Logger .getLogger(CharacterHandler.class);
25+
26+
public CharacterHandler(String charset) {
27+
super(charset);
28+
}
29+
30+
@Override
31+
public void handle(HttpExchange httpEx) throws IOException {
32+
super.handleHeader(httpEx);
33+
String content = handleRequest(httpEx);
34+
super.handleResponse(httpEx, content);
35+
}
36+
37+
/**
38+
* 处理请求。
39+
*/
40+
public String handleRequest(HttpExchange httpEx)
41+
throws UnsupportedEncodingException, IOException {
42+
InputStream ins = httpEx.getRequestBody();
43+
String content = URLDecoder.decode(
44+
IOUtils.toString(ins, _charset), _charset);
45+
_logger.info("请求内容:"+content);
46+
IOUtils.closeQuietly(ins);
47+
return content;
48+
}
49+
50+
}
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
/**
2+
* 创建时间:2016-8-5
3+
*/
4+
package cn.aofeng.demo.httpclient.server;
5+
6+
import java.io.IOException;
7+
import java.net.InetSocketAddress;
8+
9+
import org.apache.log4j.Logger;
10+
11+
import com.sun.net.httpserver.HttpServer;
12+
13+
/**
14+
* 简单的HTTP Server。
15+
*
16+
* @author <a href="mailto:[email protected]">聂勇</a>
17+
*/
18+
public class SimpleHttpServer {
19+
20+
private static Logger _logger = Logger.getLogger(SimpleHttpServer.class);
21+
22+
private static String _charset = "utf-8";
23+
24+
/**
25+
* @param args
26+
*/
27+
public static void main(String[] args) {
28+
int port = 8888;
29+
try {
30+
HttpServer server = HttpServer.create(new InetSocketAddress(port), 128);
31+
server.createContext("/get", new CharacterHandler(_charset));
32+
server.createContext("/post", new CharacterHandler(_charset));
33+
server.start();
34+
_logger.info("http server already started, listen port:"+port);
35+
} catch (IOException e) {
36+
_logger.error("", e);
37+
}
38+
}
39+
40+
}

0 commit comments

Comments
 (0)