mirror of
https://github.com/Estom/notes.git
synced 2026-02-06 12:04:05 +08:00
Java内容重新整理删除过期的东西
This commit is contained in:
85
Java/JavaDemo/codedemo/httpclient/FluentApi.java
Normal file
85
Java/JavaDemo/codedemo/httpclient/FluentApi.java
Normal file
@@ -0,0 +1,85 @@
|
||||
/**
|
||||
* 创建时间:2016-8-5
|
||||
*/
|
||||
package cn.aofeng.demo.httpclient;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.Charset;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import org.apache.http.NameValuePair;
|
||||
import org.apache.http.client.ClientProtocolException;
|
||||
import org.apache.http.client.fluent.Request;
|
||||
import org.apache.http.client.fluent.Response;
|
||||
import org.apache.http.message.BasicNameValuePair;
|
||||
import org.apache.log4j.Logger;
|
||||
|
||||
import cn.aofeng.demo.httpclient.server.SimpleHttpServer;
|
||||
|
||||
/**
|
||||
* 使用Fluent API快速地进行简单的HTTP的请求和响应处理,启动{@link SimpleHttpServer}作为请求的服务端。
|
||||
*
|
||||
* @author <a href="mailto:aofengblog@163.com">聂勇</a>
|
||||
*/
|
||||
public class FluentApi {
|
||||
|
||||
private static Logger _logger = Logger.getLogger(FluentApi.class);
|
||||
|
||||
private static String _targetHost = "http://127.0.0.1:8888";
|
||||
|
||||
private static String _charset = "utf-8";
|
||||
|
||||
/**
|
||||
* HTTP GET请求,关闭Keep-Alive。
|
||||
*
|
||||
* @param targetUrl 请求的地址
|
||||
* @param charset 将响应流转换成字符串时使用的编码
|
||||
*/
|
||||
public static void get(String targetUrl, String charset) {
|
||||
Response response = null;
|
||||
try {
|
||||
response = Request.Get(targetUrl).setHeader("Connection", "close").execute();
|
||||
String content = response.returnContent().asString(Charset.forName(charset));
|
||||
_logger.info(content);
|
||||
} catch (ClientProtocolException e) {
|
||||
_logger.error("协议问题", e);
|
||||
} catch (IOException e) {
|
||||
_logger.error("连接服务器或读取响应出错", e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* HTTP POST请求,默认开启Keep-Alive,表单数据使用utf-8编码。
|
||||
*
|
||||
* @param targetUrl 请求的地址
|
||||
* @param charset 请求表单内容处理和将响应流转换成字符串时使用的编码
|
||||
*/
|
||||
public static void post(String targetUrl, String charset) {
|
||||
List<NameValuePair> form = new ArrayList<NameValuePair>();
|
||||
form.add(new BasicNameValuePair("hello", "喂"));
|
||||
form.add(new BasicNameValuePair("gogogo", "走走走"));
|
||||
|
||||
Response response = null;
|
||||
try {
|
||||
response = Request.Post(targetUrl)
|
||||
.bodyForm(form, Charset.forName(charset))
|
||||
.execute();
|
||||
String content = response.returnContent().asString(Charset.forName(charset));
|
||||
_logger.info(content);
|
||||
} catch (ClientProtocolException e) {
|
||||
_logger.error("协议问题", e);
|
||||
} catch (IOException e) {
|
||||
_logger.error("连接服务器或读取响应出错", e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param args
|
||||
*/
|
||||
public static void main(String[] args) {
|
||||
get(_targetHost+"/get", _charset);
|
||||
post(_targetHost+"/post", _charset);
|
||||
}
|
||||
|
||||
}
|
||||
110
Java/JavaDemo/codedemo/httpclient/HttpClientBasic.java
Normal file
110
Java/JavaDemo/codedemo/httpclient/HttpClientBasic.java
Normal file
@@ -0,0 +1,110 @@
|
||||
/**
|
||||
* 创建时间:2016-2-23
|
||||
*/
|
||||
package cn.aofeng.demo.httpclient;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.net.URISyntaxException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import org.apache.http.Header;
|
||||
import org.apache.http.HttpEntity;
|
||||
import org.apache.http.NameValuePair;
|
||||
import org.apache.http.StatusLine;
|
||||
import org.apache.http.client.ClientProtocolException;
|
||||
import org.apache.http.client.entity.UrlEncodedFormEntity;
|
||||
import org.apache.http.client.methods.CloseableHttpResponse;
|
||||
import org.apache.http.client.methods.HttpGet;
|
||||
import org.apache.http.client.methods.HttpPost;
|
||||
import org.apache.http.entity.ContentType;
|
||||
import org.apache.http.entity.FileEntity;
|
||||
import org.apache.http.impl.client.CloseableHttpClient;
|
||||
import org.apache.http.impl.client.HttpClients;
|
||||
import org.apache.http.message.BasicNameValuePair;
|
||||
import org.apache.http.util.EntityUtils;
|
||||
import org.apache.log4j.Logger;
|
||||
|
||||
/**
|
||||
* HttpClient的基本操作。
|
||||
*
|
||||
* @author <a href="mailto:aofengblog@163.com">聂勇</a>
|
||||
*/
|
||||
public class HttpClientBasic {
|
||||
|
||||
private static Logger _logger = Logger.getLogger(HttpClientBasic.class);
|
||||
|
||||
private static String _targetHost = "http://127.0.0.1:8888";
|
||||
|
||||
private static String _charset = "utf-8";
|
||||
|
||||
public void get() throws URISyntaxException, ClientProtocolException, IOException {
|
||||
CloseableHttpClient client = HttpClients.createDefault();
|
||||
HttpGet get = new HttpGet(_targetHost+"/get");
|
||||
CloseableHttpResponse response = client.execute(get);
|
||||
processResponse(response);
|
||||
}
|
||||
|
||||
public void post() throws ClientProtocolException, IOException {
|
||||
List<NameValuePair> params = new ArrayList<NameValuePair>();
|
||||
params.add(new BasicNameValuePair("chinese", "中文"));
|
||||
params.add(new BasicNameValuePair("english", "英文"));
|
||||
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params, _charset);
|
||||
|
||||
CloseableHttpClient client = HttpClients.createDefault();
|
||||
HttpPost post = new HttpPost(_targetHost+"/post");
|
||||
post.addHeader("Cookie", "character=abcdefghijklmnopqrstuvwxyz; sign=abc-123-jkl-098");
|
||||
post.setEntity(entity);
|
||||
CloseableHttpResponse response = client.execute(post);
|
||||
processResponse(response);
|
||||
}
|
||||
|
||||
public void sendFile(String filePath) throws UnsupportedOperationException, IOException {
|
||||
CloseableHttpClient client = HttpClients.createDefault();
|
||||
HttpPost post = new HttpPost(_targetHost+"/file");
|
||||
File file = new File(filePath);
|
||||
FileEntity entity = new FileEntity(file, ContentType.create(ContentType.TEXT_PLAIN.getMimeType(), _charset));
|
||||
post.setEntity(entity);
|
||||
CloseableHttpResponse response = client.execute(post);
|
||||
processResponse(response);
|
||||
}
|
||||
|
||||
private void processResponse(CloseableHttpResponse response)
|
||||
throws UnsupportedOperationException, IOException {
|
||||
try {
|
||||
// 获取响应头
|
||||
Header[] headers = response.getAllHeaders();
|
||||
for (Header header : headers) {
|
||||
_logger.info(header.getName() + ":" + header.getValue());
|
||||
}
|
||||
|
||||
// 获取状态信息
|
||||
StatusLine sl =response.getStatusLine();
|
||||
_logger.info( String.format("ProtocolVersion:%s, StatusCode:%d, Desc:%s",
|
||||
sl.getProtocolVersion().toString(), sl.getStatusCode(), sl.getReasonPhrase()) );
|
||||
|
||||
// 获取响应内容
|
||||
HttpEntity entity = response.getEntity();
|
||||
_logger.info( String.format("ContentType:%s, Length:%d, Encoding:%s",
|
||||
null == entity.getContentType() ? "" : entity.getContentType().getValue(),
|
||||
entity.getContentLength(),
|
||||
null == entity.getContentEncoding() ? "" : entity.getContentEncoding().getValue()) );
|
||||
_logger.info(EntityUtils.toString(entity, _charset));
|
||||
// _logger.info( IOUtils.toString(entity.getContent(), _charset) ); // 大部分情况下效果与上行语句等同,但实现上的编码处理不同
|
||||
} finally {
|
||||
response.close();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param args
|
||||
*/
|
||||
public static void main(String[] args) throws Exception {
|
||||
HttpClientBasic basic = new HttpClientBasic();
|
||||
// basic.get();
|
||||
// basic.post();
|
||||
basic.sendFile("/devdata/projects/open_source/mine/JavaTutorial/LICENSE");
|
||||
}
|
||||
|
||||
}
|
||||
9
Java/JavaDemo/codedemo/httpclient/README.md
Normal file
9
Java/JavaDemo/codedemo/httpclient/README.md
Normal file
@@ -0,0 +1,9 @@
|
||||
#HTTP
|
||||
##HTTP客户端
|
||||
###代码
|
||||
* [使用Fluent API发起HTTP请求(Get和Post)](cn/aofeng/demo/httpclient/FluentApi.java)
|
||||
* [使用HttpClient发起HTTP请求(Get, Post和上传文件)](cn/aofeng/demo/httpclient/FluentApi.java)
|
||||
|
||||
##HTTP服务端
|
||||
###代码
|
||||
* [使用JDK中的API建立简单的HTTP Server](src/cn/aofeng/demo/httpclient/SimpleHttpServer.java)
|
||||
@@ -0,0 +1,71 @@
|
||||
/**
|
||||
* 创建时间:2016-8-18
|
||||
*/
|
||||
package cn.aofeng.demo.httpclient.server;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.OutputStream;
|
||||
import java.io.UnsupportedEncodingException;
|
||||
import java.net.InetSocketAddress;
|
||||
import java.net.URI;
|
||||
import java.util.List;
|
||||
import java.util.Map.Entry;
|
||||
import java.util.Set;
|
||||
|
||||
import org.apache.commons.io.IOUtils;
|
||||
import org.apache.log4j.Logger;
|
||||
|
||||
import com.sun.net.httpserver.Headers;
|
||||
import com.sun.net.httpserver.HttpExchange;
|
||||
import com.sun.net.httpserver.HttpHandler;
|
||||
|
||||
/**
|
||||
* @author <a href="mailto:aofengblog@163.com">聂勇</a>
|
||||
*/
|
||||
public abstract class AbstractHandler implements HttpHandler {
|
||||
|
||||
private static Logger _logger = Logger.getLogger(AbstractHandler.class);
|
||||
|
||||
protected String _charset = "utf-8";
|
||||
|
||||
public AbstractHandler(String charset) {
|
||||
this._charset = charset;
|
||||
}
|
||||
|
||||
/**
|
||||
* 处理请求头。
|
||||
*/
|
||||
public void handleHeader(HttpExchange httpEx) {
|
||||
InetSocketAddress remoteAddress = httpEx.getRemoteAddress();
|
||||
_logger.info("收到来自"+remoteAddress.getAddress().getHostAddress()+":"+remoteAddress.getPort()+"的请求");
|
||||
|
||||
URI rUri = httpEx.getRequestURI();
|
||||
_logger.info("请求地址:"+rUri.toString());
|
||||
|
||||
String method = httpEx.getRequestMethod();
|
||||
_logger.info("请求方法:"+method);
|
||||
|
||||
Headers headers = httpEx.getRequestHeaders();
|
||||
Set<Entry<String, List<String>>> headerSet = headers.entrySet();
|
||||
_logger.info("请求头:");
|
||||
for (Entry<String, List<String>> header : headerSet) {
|
||||
_logger.info(header.getKey()+":"+header.getValue());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 处理响应。
|
||||
*/
|
||||
public void handleResponse(HttpExchange httpEx, String content)
|
||||
throws UnsupportedEncodingException, IOException {
|
||||
String rc = "冒号后面是收到的请求,原样返回:"+content;
|
||||
byte[] temp = rc.getBytes(_charset);
|
||||
Headers outHeaders = httpEx.getResponseHeaders();
|
||||
outHeaders.set("ABC", "123");
|
||||
httpEx.sendResponseHeaders(200, temp.length);
|
||||
OutputStream outs = httpEx.getResponseBody();
|
||||
outs.write(temp);
|
||||
IOUtils.closeQuietly(outs);
|
||||
}
|
||||
|
||||
}
|
||||
66
Java/JavaDemo/codedemo/httpclient/server/BinaryHandler.java
Normal file
66
Java/JavaDemo/codedemo/httpclient/server/BinaryHandler.java
Normal file
@@ -0,0 +1,66 @@
|
||||
/**
|
||||
* 创建时间:2016-8-18
|
||||
*/
|
||||
package cn.aofeng.demo.httpclient.server;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.OutputStream;
|
||||
|
||||
import org.apache.commons.io.IOUtils;
|
||||
import org.apache.log4j.Logger;
|
||||
|
||||
import com.sun.net.httpserver.HttpExchange;
|
||||
import com.sun.net.httpserver.HttpHandler;
|
||||
|
||||
/**
|
||||
* 二进制处理器。
|
||||
*
|
||||
* @author <a href="mailto:aofengblog@163.com">聂勇</a>
|
||||
*/
|
||||
public class BinaryHandler extends AbstractHandler implements HttpHandler {
|
||||
|
||||
private static Logger _logger = Logger.getLogger(BinaryHandler.class);
|
||||
|
||||
private String _dir = "/home/nieyong/temp/JavaTutorial";
|
||||
|
||||
public BinaryHandler(String charset) {
|
||||
super(charset);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void handle(HttpExchange httpEx) throws IOException {
|
||||
super.handleHeader(httpEx);
|
||||
handleRequest(httpEx);
|
||||
String content = "收到一个二进制的请求";
|
||||
super.handleResponse(httpEx, content);
|
||||
}
|
||||
|
||||
/**
|
||||
* 处理请求。
|
||||
* @throws IOException
|
||||
*/
|
||||
public String handleRequest(HttpExchange httpEx) throws IOException {
|
||||
OutputStream outs = null;
|
||||
InputStream ins = null;
|
||||
try {
|
||||
File file = new File(_dir, ""+System.currentTimeMillis());
|
||||
if (!file.exists()) {
|
||||
file.createNewFile();
|
||||
}
|
||||
outs = new FileOutputStream(file);
|
||||
ins = httpEx.getRequestBody();
|
||||
IOUtils.copyLarge(ins, outs);
|
||||
} catch (Exception e) {
|
||||
_logger.error("read request or write file occurs error", e);
|
||||
} finally {
|
||||
IOUtils.closeQuietly(ins);
|
||||
IOUtils.closeQuietly(outs);
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
/**
|
||||
* 创建时间:2016-8-18
|
||||
*/
|
||||
package cn.aofeng.demo.httpclient.server;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.UnsupportedEncodingException;
|
||||
import java.net.URLDecoder;
|
||||
|
||||
import org.apache.commons.io.IOUtils;
|
||||
import org.apache.log4j.Logger;
|
||||
|
||||
import com.sun.net.httpserver.HttpExchange;
|
||||
import com.sun.net.httpserver.HttpHandler;
|
||||
|
||||
/**
|
||||
* 字符串处理器。
|
||||
*
|
||||
* @author <a href="mailto:aofengblog@163.com">聂勇</a>
|
||||
*/
|
||||
public class CharacterHandler extends AbstractHandler implements HttpHandler {
|
||||
|
||||
static Logger _logger = Logger .getLogger(CharacterHandler.class);
|
||||
|
||||
public CharacterHandler(String charset) {
|
||||
super(charset);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void handle(HttpExchange httpEx) throws IOException {
|
||||
super.handleHeader(httpEx);
|
||||
String content = handleRequest(httpEx);
|
||||
super.handleResponse(httpEx, content);
|
||||
}
|
||||
|
||||
/**
|
||||
* 处理请求。
|
||||
*/
|
||||
public String handleRequest(HttpExchange httpEx)
|
||||
throws UnsupportedEncodingException, IOException {
|
||||
InputStream ins = httpEx.getRequestBody();
|
||||
String content = URLDecoder.decode(
|
||||
IOUtils.toString(ins, _charset), _charset);
|
||||
_logger.info("请求内容:"+content);
|
||||
IOUtils.closeQuietly(ins);
|
||||
return content;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
/**
|
||||
* 创建时间:2016-8-5
|
||||
*/
|
||||
package cn.aofeng.demo.httpclient.server;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.InetSocketAddress;
|
||||
|
||||
import org.apache.log4j.Logger;
|
||||
|
||||
import com.sun.net.httpserver.HttpServer;
|
||||
|
||||
/**
|
||||
* 简单的HTTP Server。
|
||||
*
|
||||
* @author <a href="mailto:aofengblog@163.com">聂勇</a>
|
||||
*/
|
||||
public class SimpleHttpServer {
|
||||
|
||||
private static Logger _logger = Logger.getLogger(SimpleHttpServer.class);
|
||||
|
||||
private static String _charset = "utf-8";
|
||||
|
||||
/**
|
||||
* @param args
|
||||
*/
|
||||
public static void main(String[] args) {
|
||||
int port = 8888;
|
||||
try {
|
||||
HttpServer server = HttpServer.create(new InetSocketAddress(port), 128);
|
||||
server.createContext("/get", new CharacterHandler(_charset));
|
||||
server.createContext("/post", new CharacterHandler(_charset));
|
||||
server.createContext("/file", new BinaryHandler(_charset));
|
||||
server.start();
|
||||
_logger.info("http server already started, listen port:"+port);
|
||||
} catch (IOException e) {
|
||||
_logger.error("", e);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user