一言不合就写socket的post和get请求(拼内容,然后发出去即可)

一言不合就写socket的post和get请求。写个桌面程序,利用java写get和post请求。测试成功;

SocketReq.java

 

[java] view plain copy
 
  1. package com.test.CipherIndex;  
  2.   
  3. import java.io.BufferedInputStream;  
  4. import java.io.BufferedReader;  
  5. import java.io.BufferedWriter;  
  6. import java.io.ByteArrayOutputStream;  
  7. import java.io.DataOutputStream;  
  8. import java.io.IOException;  
  9. import java.io.InputStream;  
  10. import java.io.InputStreamReader;  
  11. import java.io.OutputStreamWriter;  
  12. import java.net.InetSocketAddress;  
  13. import java.net.Socket;  
  14. import java.net.SocketAddress;  
  15. import java.net.URL;  
  16. import java.net.URLEncoder;  
  17. import java.net.UnknownHostException;  
  18. import java.security.KeyManagementException;  
  19. import java.security.NoSuchAlgorithmException;  
  20. import java.security.Security;  
  21. import java.security.cert.CertificateException;  
  22. import java.security.cert.X509Certificate;  
  23.   
  24. import javax.net.ssl.*;  
  25. import com.sun.net.ssl.internal.www.protocol.https.*;  
  26.   
  27. public class SocketReq {  
  28.     private int port;  
  29.     private String host;  
  30.     private Socket socket;  
  31.     private BufferedReader bufferedReader;  
  32.     private BufferedWriter bufferedWriter;  
  33.   
  34.     public SocketReq() {  
  35.   
  36.     }  
  37.   
  38.     public SocketReq(String host, int port) {  
  39.         this.host = host;  
  40.         this.port = port;  
  41.   
  42.         try {  
  43.             socket = (SSLSocket) ((SSLSocketFactory) SSLSocketFactory  
  44.                     .getDefault()).createSocket(this.host, this.port);  
  45.         } catch (UnknownHostException e1) {  
  46.             // TODO Auto-generated catch block  
  47.             e1.printStackTrace();  
  48.         } catch (IOException e1) {  
  49.             // TODO Auto-generated catch block  
  50.             e1.printStackTrace();  
  51.         }  
  52.   
  53.         // SSLSocket  
  54.         // try {  
  55.         // socket = (SSLSocket) factory.createSocket("https://192.168.111.30",  
  56.         // 443);  
  57.         // } catch (UnknownHostException e) {  
  58.         // // TODO Auto-generated catch block  
  59.         // e.printStackTrace();  
  60.         // } catch (IOException e) {  
  61.         // // TODO Auto-generated catch block  
  62.         // e.printStackTrace();  
  63.         // }  
  64.   
  65.         // socket = new Socket();  
  66.   
  67.     }  
  68.   
  69.     public void sendGet(String path) throws IOException {  
  70.   
  71.         // 自定义的管理器  
  72.         X509TrustManager xtm = new TrustAnyTrustManager();  
  73.         TrustManager mytm[] = { xtm };  
  74.         // 得到上下文  
  75.         SSLContext ctx;  
  76.         try {  
  77.             ctx = SSLContext.getInstance("SSL");  
  78.   
  79.             // 初始化  
  80.   
  81.             ctx.init(null, mytm, null);  
  82.   
  83.             // 获得工厂  
  84.             SSLSocketFactory factory = ctx.getSocketFactory();  
  85.   
  86.             // 从工厂获得Socket连接  
  87.             Socket socket = factory.createSocket(this.host, 443);  
  88.   
  89.             // 剩下的就和普通的Socket操作一样了  
  90.             BufferedWriter out = new BufferedWriter(new OutputStreamWriter(  
  91.                     socket.getOutputStream()));  
  92.             BufferedReader in = new BufferedReader(new InputStreamReader(  
  93.                     socket.getInputStream()));  
  94.             out.write("GET " + path + " HTTP/1.0\n\n");  
  95.             out.flush();  
  96.             System.out.println("start   work!");  
  97.             String line;  
  98.             StringBuffer sb = new StringBuffer();  
  99.             while ((line = in.readLine()) != null) {  
  100.                 sb.append(line + "\n");  
  101.             }  
  102.             out.close();  
  103.             in.close();  
  104.             String outcome = sb.toString();  
  105.             System.out.println(outcome);  
  106.   
  107.         } catch (NoSuchAlgorithmException e) {  
  108.             // TODO Auto-generated catch block  
  109.             e.printStackTrace();  
  110.         } catch (KeyManagementException e) {  
  111.             // TODO Auto-generated catch block  
  112.             e.printStackTrace();  
  113.         }  
  114.   
  115.     }  
  116.   
  117.     public void sendPost(String path) throws IOException {  
  118.         // String path = "/zhigang/postDemo.php";  
  119.         String data = URLEncoder.encode("name", "utf-8") + "="  
  120.                 + URLEncoder.encode("gloomyfish", "utf-8") + "&"  
  121.                 + URLEncoder.encode("age", "utf-8") + "="  
  122.                 + URLEncoder.encode("32", "utf-8");  
  123.         // String data = "name=zhigang_jia";  
  124.         SocketAddress dest = new InetSocketAddress(this.host, this.port);  
  125.         socket.connect(dest);  
  126.         OutputStreamWriter streamWriter = new OutputStreamWriter(  
  127.                 socket.getOutputStream(), "utf-8");  
  128.         bufferedWriter = new BufferedWriter(streamWriter);  
  129.   
  130.         bufferedWriter.write("POST " + path + " HTTP/1.1\r\n");  
  131.         bufferedWriter.write("Host: " + this.host + "\r\n");  
  132.         bufferedWriter.write("Content-Length: " + data.length() + "\r\n");  
  133.         bufferedWriter  
  134.                 .write("Content-Type: application/x-www-form-urlencoded\r\n");  
  135.         bufferedWriter.write("\r\n");  
  136.         bufferedWriter.write(data);  
  137.         bufferedWriter.flush();  
  138.         bufferedWriter.write("\r\n");  
  139.         bufferedWriter.flush();  
  140.   
  141.         BufferedInputStream streamReader = new BufferedInputStream(  
  142.                 socket.getInputStream());  
  143.         bufferedReader = new BufferedReader(new InputStreamReader(streamReader,  
  144.                 "utf-8"));  
  145.         String line = null;  
  146.         while ((line = bufferedReader.readLine()) != null) {  
  147.             System.out.println(line.getBytes("utf-8"));  
  148.         }  
  149.         bufferedReader.close();  
  150.         bufferedWriter.close();  
  151.         socket.close();  
  152.     }  
  153.   
  154.     public static byte[] post(String url, String content, String charset)  
  155.             throws NoSuchAlgorithmException, KeyManagementException,  
  156.             IOException {  
  157.         byte[] ret = null;  
  158.   
  159.         try {  
  160.             SSLContext sc = SSLContext.getInstance("SSL");  
  161.             sc.init(null, new TrustManager[] { new TrustAnyTrustManager() },  
  162.                     new java.security.SecureRandom());  
  163.   
  164.             URL console = new URL(url);  
  165.             HttpsURLConnection conn = (HttpsURLConnection) console  
  166.                     .openConnection();  
  167.             conn.setRequestMethod("POST");  
  168.   
  169.             conn.setRequestProperty("Connection", "Keep-Alive");  
  170.             conn.setRequestProperty("Charset", "UTF-8");  
  171.             conn.setRequestProperty("Content-type",  
  172.                     "multipart/form-data;boundary=*****");  
  173.             // 在与服务器连接之前,设置一些网络参数  
  174.             conn.setConnectTimeout(10000);  
  175.   
  176.             conn.setDoOutput(true);  
  177.             conn.setSSLSocketFactory(sc.getSocketFactory());  
  178.             conn.setHostnameVerifier(new TrustAnyHostnameVerifier());  
  179.             conn.connect();  
  180.             DataOutputStream out = new DataOutputStream(conn.getOutputStream());  
  181.   
  182.             out.write(content.getBytes(charset));  
  183.             // 刷新、关闭  
  184.             out.flush();  
  185.             out.close();  
  186.             InputStream is = conn.getInputStream();  
  187.             try {  
  188.                 if (is != null) {  
  189.                     ByteArrayOutputStream outStream = new ByteArrayOutputStream();  
  190.                     byte[] buffer = new byte[1024];  
  191.                     int len = 0;  
  192.                     while ((len = is.read(buffer)) != -1) {  
  193.                         outStream.write(buffer, 0, len);  
  194.                     }  
  195.                     // is.close();  
  196.                     ret = outStream.toByteArray();  
  197.                 }  
  198.             } catch (Exception e) {  
  199.                 e.printStackTrace();  
  200.             } finally {  
  201.                 if (null != is) {  
  202.                     is.close();  
  203.                 }  
  204.             }  
  205.   
  206.         } catch (Exception e) {  
  207.             e.printStackTrace();  
  208.         }  
  209.         return ret;  
  210.     }  
  211.   
  212.     public static byte[] get(String url, String content, String charset)  
  213.             throws NoSuchAlgorithmException, KeyManagementException,  
  214.             IOException {  
  215.         byte[] ret = null;  
  216.         try {  
  217.             SSLContext sc = SSLContext.getInstance("SSL");  
  218.             sc.init(null, new TrustManager[] { new TrustAnyTrustManager() },  
  219.                     new java.security.SecureRandom());  
  220.   
  221.             URL console = new URL(url);  
  222.             HttpsURLConnection conn = (HttpsURLConnection) console  
  223.                     .openConnection();  
  224.             conn.setRequestMethod("GET");  
  225.   
  226.             // conn.setRequestProperty("Content-type",  
  227.             // "multipart/form-data;boundary=*****");  
  228.             // 在与服务器连接之前,设置一些网络参数  
  229.             conn.setConnectTimeout(10000);  
  230.             conn.setReadTimeout(10000);  
  231.             // conn.setDoOutput(true);  
  232.             conn.setSSLSocketFactory(sc.getSocketFactory());  
  233.             conn.setHostnameVerifier(new TrustAnyHostnameVerifier());  
  234.   
  235.             conn.setRequestProperty("Connection", "Keep-Alive");  
  236.             conn.setRequestProperty("Charset", "UTF-8");  
  237.             conn.setRequestProperty("Content-Type",  
  238.                     "application/x-www-form-urlencoded");  
  239.   
  240.             conn.connect();  
  241.   
  242.             InputStream is = conn.getInputStream();  
  243.   
  244.             try {  
  245.                 if (is != null) {  
  246.                     ByteArrayOutputStream outStream = new ByteArrayOutputStream();  
  247.                     byte[] buffer = new byte[1024];  
  248.                     int len = 0;  
  249.                     while ((len = is.read(buffer)) != -1) {  
  250.                         outStream.write(buffer, 0, len);  
  251.                     }  
  252.                     ret = outStream.toByteArray();  
  253.                 }  
  254.             } catch (Exception e) {  
  255.                 e.printStackTrace();  
  256.             } finally {  
  257.                 if (null != is) {  
  258.                     is.close();  
  259.                 }  
  260.             }  
  261.         } catch (Exception e) {  
  262.             e.printStackTrace();  
  263.         }  
  264.         // 关闭输入流  
  265.   
  266.         return ret;  
  267.     }  
  268.   
  269.     private static class TrustAnyTrustManager implements X509TrustManager {  
  270.         TrustAnyTrustManager() {  
  271.             // 这里可以进行证书的初始化操作  
  272.         }  
  273.   
  274.         public void checkClientTrusted(X509Certificate[] chain, String authType)  
  275.                 throws CertificateException {  
  276.             // System.out.println("检查客户端的可信任状态...");  
  277.         }  
  278.   
  279.         public void checkServerTrusted(X509Certificate[] chain, String authType)  
  280.                 throws CertificateException {  
  281.             // System.out.println("检查服务器的可信任状态");  
  282.         }  
  283.   
  284.         public X509Certificate[] getAcceptedIssuers() {  
  285.             // System.out.println("获取接受的发行商数组...");  
  286.             return new X509Certificate[] {};  
  287.         }  
  288.     }  
  289.   
  290.     private static class TrustAnyHostnameVerifier implements HostnameVerifier {  
  291.         public boolean verify(String hostname, SSLSession session) {  
  292.             return true;  
  293.         }  
  294.     }  
  295. }  


CipherMain.java

 

 

[java] view plain copy
 
    1. package com.test.CipherIndex;  
    2.   
    3. import java.io.IOException;  
    4. import java.io.UnsupportedEncodingException;  
    5. import java.security.KeyManagementException;  
    6. import java.security.NoSuchAlgorithmException;  
    7.   
    8. import com.test.MainTest;  
    9.   
    10. public class CipherMain {  
    11.   
    12.     public static void main(String[] args) {  
    13.           
    14.         CipherMain cm = new CipherMain();  
    15. //      cm.test_post();  
    16.         cm.test_get();  
    17.     }  
    18.   
    19.     void test_post() {  
    20.   
    21.         SocketReq socketreq = new SocketReq();  
    22.         try {  
    23.             byte[] getret = socketreq.get(  
    24.                     "https://192.168.111.30/Mycloud/index.html", "1", "utf-8");  
    25.             String getstrRead = new String(getret, "utf-8");  
    26.             System.out.println(getstrRead);  
    27.         } catch (KeyManagementException e) {  
    28.             // TODO Auto-generated catch block  
    29.             e.printStackTrace();  
    30.         } catch (NoSuchAlgorithmException e) {  
    31.             // TODO Auto-generated catch block  
    32.             e.printStackTrace();  
    33.         }  
    34.         catch (UnsupportedEncodingException e) {  
    35.             // TODO Auto-generated catch block  
    36.             e.printStackTrace();  
    37.         } catch (IOException e) {  
    38.             // TODO Auto-generated catch block  
    39.             e.printStackTrace();  
    40.         }  
    41.     }  
    42.   
    43.     void test_get() {  
    44.   
    45.         SocketReq socketreq = new SocketReq();  
    46.         try {  
    47.             byte[] ret = socketreq.post(  
    48.                     "https://192.168.111.30/Mycloud/index.html", "1", "utf-8");  
    49.   
    50.             String strRead = new String(ret, "utf-8");  
    51.   
    52.             System.out.println(strRead);  
    53.   
    54.         } catch (KeyManagementException e) {  
    55.             // TODO Auto-generated catch block  
    56.             e.printStackTrace();  
    57.         } catch (NoSuchAlgorithmException e) {  
    58.             // TODO Auto-generated catch block  
    59.             e.printStackTrace();  
    60.         }  
    61.         catch (UnsupportedEncodingException e) {  
    62.             // TODO Auto-generated catch block  
    63.             e.printStackTrace();  
    64.         } catch (IOException e) {  
    65.             // TODO Auto-generated catch block  
    66.             e.printStackTrace();  
    67.         }  
    68.     }  
    69. }  

 

http://blog.csdn.net/bupt073114/article/details/52092489

posted @ 2017-12-06 23:37  findumars  Views(381)  Comments(0Edit  收藏  举报