jdk http server test
2016-03-10 16:05
381 查看
package com.cyyun.xc.command.util; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.net.InetSocketAddress; import com.sun.net.httpserver.HttpExchange; import com.sun.net.httpserver.HttpHandler; import com.sun.net.httpserver.HttpServer; import com.sun.net.httpserver.spi.HttpServerProvider; /** * @project SimpleHttpServer * @author sunnylocus * @vresion 1.0 2009-9-2 * @description 自定义的http服务器 */ public class MyHttpServer { // 启动服务,监听来自客户端的请求 public static void httpserverService() throws IOException { HttpServerProvider provider = HttpServerProvider.provider(); HttpServer httpserver = provider.createHttpServer( new InetSocketAddress(6666), 100);// 监听端口6666,能同时接 受100个请求 httpserver.createContext("/myApp", new MyHttpHandler()); httpserver.setExecutor(null); httpserver.start(); System.out.println("server started"); } // Http请求处理类 static class MyHttpHandler implements HttpHandler { public void handle(HttpExchange httpExchange) throws IOException { String responseMsg = "ok"; // 响应信息 System.out.println("httpExchange.getRequestMethod() "+httpExchange.getRequestMethod()); System.out.println("httpExchange.getRequestURI() "+httpExchange.getRequestURI()); InputStream in = httpExchange.getRequestBody(); // 获得输入流 BufferedReader reader = new BufferedReader( new InputStreamReader(in)); String temp = null; while ((temp = reader.readLine()) != null) { System.out.println("client request:" + temp); } httpExchange.sendResponseHeaders(200, responseMsg.length()); // 设置响应头属性及响应信息的长度 OutputStream out = httpExchange.getResponseBody(); // 获得输出流 out.write(responseMsg.getBytes()); out.flush(); httpExchange.close(); } } public static void main(String[] args) throws IOException { httpserverService(); } }
package com.cyyun.xc.command.util; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.URI; import java.net.URISyntaxException; import java.security.KeyStore; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLException; import javax.net.ssl.SSLSession; import javax.net.ssl.SSLSocket; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; import org.apache.commons.lang3.StringUtils; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.ParseException; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpUriRequest; import org.apache.http.conn.scheme.Scheme; import org.apache.http.conn.ssl.SSLSocketFactory; import org.apache.http.conn.ssl.X509HostnameVerifier; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.message.BasicNameValuePair; import org.apache.http.params.CoreConnectionPNames; import org.apache.http.protocol.HTTP; import org.apache.http.util.EntityUtils; import org.apache.log4j.Logger; public class HttpXmlClient { private static Logger log = Logger.getLogger(HttpXmlClient.class); public static String post(String url, Map<String, String> params) { DefaultHttpClient httpclient = new DefaultHttpClient(); String body = null; log.info("create httppost:" + url); HttpPost post = postForm(url, params); body = invoke(httpclient, post); httpclient.getConnectionManager().shutdown(); return body; } public static String get(String url) { DefaultHttpClient httpclient = new DefaultHttpClient(); // 请求超时 httpclient.getParams().setParameter( CoreConnectionPNames.CONNECTION_TIMEOUT, 30000); // 读取超时 httpclient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 30000); String body = null; log.info("create httppost:" + url); HttpGet get = new HttpGet(url); body = invoke(httpclient, get); httpclient.getConnectionManager().shutdown(); return body; } public static String invoke(DefaultHttpClient httpclient, HttpUriRequest httpost) { HttpResponse response = sendRequest(httpclient, httpost); String body = paseResponse(response); return body; } private static String paseResponse(HttpResponse response) { log.info("get response from http server.."); HttpEntity entity = response.getEntity(); log.info("response status: " + response.getStatusLine()); String charset = EntityUtils.getContentCharSet(entity); log.info(charset); String body = null; try { body = EntityUtils.toString(entity); log.info(body); } catch (ParseException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return body; } public static void main(String[] args) { String url = "http://127.0.0.1:6666/myApp?123123"; //get(url); Map<String,String> params= new LinkedHashMap<String, String>(); for(int i=0;i<100;i++){ params.put("name"+i, "1234"); } post(url, params); } public static void setHttps(DefaultHttpClient httpclient, File file) { try { // 获得密匙库 KeyStore trustStore = KeyStore.getInstance(KeyStore .getDefaultType()); FileInputStream instream = new FileInputStream(file); // 密匙库的密码 trustStore.load(instream, "1qaz2wsx".toCharArray()); // 注册密匙库 SSLSocketFactory socketFactory = new SSLSocketFactory(trustStore); // 不校验域名 socketFactory .setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); Scheme sch = new Scheme("https", 443, socketFactory); httpclient.getConnectionManager().getSchemeRegistry().register(sch); } catch (Exception e) { log.error(e); } } public static void setHttps2(DefaultHttpClient httpclient, File file) { try { X509TrustManager trustManager = new X509TrustManager() { @Override public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { } @Override public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { } @Override public X509Certificate[] getAcceptedIssuers() { return null; } }; // 创建HostnameVerifier // 用于解决javax.net.ssl.SSLException: hostname in certificate didn't // match: // <123.125.97.66> != <123.125.97.241> X509HostnameVerifier hostnameVerifier = new X509HostnameVerifier() { @Override public void verify(String host, SSLSocket ssl) throws IOException { } @Override public void verify(String host, X509Certificate cert) throws SSLException { } @Override public void verify(String host, String[] cns, String[] subjectAlts) throws SSLException { } @Override public boolean verify(String arg0, SSLSession arg1) { return true; } }; // TLS1.0与SSL3.0基本上没有太大的差别,可粗略理解为TLS是SSL的继承者,但它们使用的是相同的SSLContext SSLContext sslContext = SSLContext .getInstance(SSLSocketFactory.TLS); // 使用TrustManager来初始化该上下文,TrustManager只是被SSL的Socket所使用 sslContext.init(null, new TrustManager[] { trustManager }, null); // 创建SSLSocketFactory SSLSocketFactory socketFactory = new SSLSocketFactory(sslContext, hostnameVerifier); // 通过SchemeRegistry将SSLSocketFactory注册到HttpClient上 httpclient.getConnectionManager().getSchemeRegistry() .register(new Scheme("https", 443, socketFactory)); } catch (Exception e) { log.error(e); } } public static HttpResponse sendRequest(DefaultHttpClient httpclient, HttpUriRequest httpost) { log.info("execute post..."); HttpResponse response = null; try { response = httpclient.execute(httpost); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { } return response; } public static HttpPost postForm(String url, Map<String, String> params) { HttpPost httpost = new HttpPost(url); // httpost.setHeaders(headers); List<NameValuePair> nvps = new ArrayList<NameValuePair>(); Set<String> keySet = params.keySet(); for (String key : keySet) { nvps.add(new BasicNameValuePair(key, params.get(key))); } try { log.info("set utf-8 form entity to httppost"); httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8)); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return httpost; } private static HttpPost postForm(String url, Map<String, String> params, HttpPost httpost) { // HttpPost httpost = new HttpPost(url); try { httpost.setURI(new URI(url)); } catch (URISyntaxException e1) { e1.printStackTrace(); } List<NameValuePair> nvps = new ArrayList<NameValuePair>(); Set<String> keySet = params.keySet(); for (String key : keySet) { nvps.add(new BasicNameValuePair(key, params.get(key))); } try { log.info("set utf-8 form entity to httppost"); httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8)); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return httpost; } public static String checkIp(DefaultHttpClient httpclient, String ip, String prot) { String rs = null; String url = "http://web.chacuo.net/netproxycheck"; Map<String, String> dataMap = new HashMap<String, String>(); dataMap.put("data", ip.trim()); dataMap.put("type", "proxycheck"); dataMap.put("arg", "p=" + prot.trim() + "_t=1_o=3"); // log.error("ip map :" + dataMap); try { HttpPost httpPost = postForm(url, dataMap); rs = invoke(httpclient, httpPost); rs = encodingtoStr(rs); } catch (Exception e) { log.error("检测ip出错", e); } return rs; } /** * 汉字转Unicode * * @param s * @return */ public static String gbEncoding(final String s) { if (StringUtils.isBlank(s)) { return null; } String str = ""; for (int i = 0; i < s.length(); i++) { int ch = (int) s.charAt(i); str += "\\u" + Integer.toHexString(ch); } return str; } /** * Unicode转汉字 * * @param str * @return */ public static String encodingtoStr(String str) { if (StringUtils.isBlank(str)) { return null; } Pattern pattern = Pattern.compile("(\\\\u(\\p{XDigit}{4}))"); Matcher matcher = pattern.matcher(str); char ch; while (matcher.find()) { ch = (char) Integer.parseInt(matcher.group(2), 16); str = str.replace(matcher.group(1), ch + ""); } return str; } }
相关文章推荐
- 转:Java中用HttpsURLConnection访问Https链接的问题
- Java网络编程之JavaMail发送邮件和接受邮件
- 简约之美Jodd-http--应用一箩筐
- http header 详解
- HTTP 断点续传
- Nginx 的 TCP 负载均衡介绍
- 用Apache HttpClient实现URL重定向
- TCP/IP,http,socket,长连接,短连接
- HTTP 断点续传
- 简约之美Jodd-http--深入源码理解http协议
- HttpClient连接池的三篇文章
- httpclient http连接池 源码阅读
- httpclient post 中文问题
- htmlunit 模拟登陆 https
- 使用HttpClient发送Post Http请求
- HttpClient连接池原理及一次连接时序图
- 几种通讯协议的比较RMI &gt; Httpinvoker &gt;= Hessian &gt;&gt; Burlap &gt;&gt; web service
- HttpAsyncClient的连接池使用
- http连接池使用 参数
- httpclient http连接池 demo