一言不合就写socket的post和get请求(拼内容,然后发出去即可)
一言不合就写socket的post和get请求。写个桌面程序,利用java写get和post请求。测试成功;
SocketReq.java
- package com.test.CipherIndex;
- import java.io.BufferedInputStream;
- import java.io.BufferedReader;
- import java.io.BufferedWriter;
- import java.io.ByteArrayOutputStream;
- import java.io.DataOutputStream;
- import java.io.IOException;
- import java.io.InputStream;
- import java.io.InputStreamReader;
- import java.io.OutputStreamWriter;
- import java.net.InetSocketAddress;
- import java.net.Socket;
- import java.net.SocketAddress;
- import java.net.URL;
- import java.net.URLEncoder;
- import java.net.UnknownHostException;
- import java.security.KeyManagementException;
- import java.security.NoSuchAlgorithmException;
- import java.security.Security;
- import java.security.cert.CertificateException;
- import java.security.cert.X509Certificate;
- import javax.net.ssl.*;
- import com.sun.net.ssl.internal.www.protocol.https.*;
- public class SocketReq {
- private int port;
- private String host;
- private Socket socket;
- private BufferedReader bufferedReader;
- private BufferedWriter bufferedWriter;
- public SocketReq() {
- }
- public SocketReq(String host, int port) {
- this.host = host;
- this.port = port;
- try {
- socket = (SSLSocket) ((SSLSocketFactory) SSLSocketFactory
- .getDefault()).createSocket(this.host, this.port);
- } catch (UnknownHostException e1) {
- // TODO Auto-generated catch block
- e1.printStackTrace();
- } catch (IOException e1) {
- // TODO Auto-generated catch block
- e1.printStackTrace();
- }
- // SSLSocket
- // try {
- // socket = (SSLSocket) factory.createSocket("https://192.168.111.30",
- // 443);
- // } catch (UnknownHostException e) {
- // // TODO Auto-generated catch block
- // e.printStackTrace();
- // } catch (IOException e) {
- // // TODO Auto-generated catch block
- // e.printStackTrace();
- // }
- // socket = new Socket();
- }
- public void sendGet(String path) throws IOException {
- // 自定义的管理器
- X509TrustManager xtm = new TrustAnyTrustManager();
- TrustManager mytm[] = { xtm };
- // 得到上下文
- SSLContext ctx;
- try {
- ctx = SSLContext.getInstance("SSL");
- // 初始化
- ctx.init(null, mytm, null);
- // 获得工厂
- SSLSocketFactory factory = ctx.getSocketFactory();
- // 从工厂获得Socket连接
- Socket socket = factory.createSocket(this.host, 443);
- // 剩下的就和普通的Socket操作一样了
- BufferedWriter out = new BufferedWriter(new OutputStreamWriter(
- socket.getOutputStream()));
- BufferedReader in = new BufferedReader(new InputStreamReader(
- socket.getInputStream()));
- out.write("GET " + path + " HTTP/1.0\n\n");
- out.flush();
- System.out.println("start work!");
- String line;
- StringBuffer sb = new StringBuffer();
- while ((line = in.readLine()) != null) {
- sb.append(line + "\n");
- }
- out.close();
- in.close();
- String outcome = sb.toString();
- System.out.println(outcome);
- } catch (NoSuchAlgorithmException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } catch (KeyManagementException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- public void sendPost(String path) throws IOException {
- // String path = "/zhigang/postDemo.php";
- String data = URLEncoder.encode("name", "utf-8") + "="
- + URLEncoder.encode("gloomyfish", "utf-8") + "&"
- + URLEncoder.encode("age", "utf-8") + "="
- + URLEncoder.encode("32", "utf-8");
- // String data = "name=zhigang_jia";
- SocketAddress dest = new InetSocketAddress(this.host, this.port);
- socket.connect(dest);
- OutputStreamWriter streamWriter = new OutputStreamWriter(
- socket.getOutputStream(), "utf-8");
- bufferedWriter = new BufferedWriter(streamWriter);
- bufferedWriter.write("POST " + path + " HTTP/1.1\r\n");
- bufferedWriter.write("Host: " + this.host + "\r\n");
- bufferedWriter.write("Content-Length: " + data.length() + "\r\n");
- bufferedWriter
- .write("Content-Type: application/x-www-form-urlencoded\r\n");
- bufferedWriter.write("\r\n");
- bufferedWriter.write(data);
- bufferedWriter.flush();
- bufferedWriter.write("\r\n");
- bufferedWriter.flush();
- BufferedInputStream streamReader = new BufferedInputStream(
- socket.getInputStream());
- bufferedReader = new BufferedReader(new InputStreamReader(streamReader,
- "utf-8"));
- String line = null;
- while ((line = bufferedReader.readLine()) != null) {
- System.out.println(line.getBytes("utf-8"));
- }
- bufferedReader.close();
- bufferedWriter.close();
- socket.close();
- }
- public static byte[] post(String url, String content, String charset)
- throws NoSuchAlgorithmException, KeyManagementException,
- IOException {
- byte[] ret = null;
- try {
- SSLContext sc = SSLContext.getInstance("SSL");
- sc.init(null, new TrustManager[] { new TrustAnyTrustManager() },
- new java.security.SecureRandom());
- URL console = new URL(url);
- HttpsURLConnection conn = (HttpsURLConnection) console
- .openConnection();
- conn.setRequestMethod("POST");
- conn.setRequestProperty("Connection", "Keep-Alive");
- conn.setRequestProperty("Charset", "UTF-8");
- conn.setRequestProperty("Content-type",
- "multipart/form-data;boundary=*****");
- // 在与服务器连接之前,设置一些网络参数
- conn.setConnectTimeout(10000);
- conn.setDoOutput(true);
- conn.setSSLSocketFactory(sc.getSocketFactory());
- conn.setHostnameVerifier(new TrustAnyHostnameVerifier());
- conn.connect();
- DataOutputStream out = new DataOutputStream(conn.getOutputStream());
- out.write(content.getBytes(charset));
- // 刷新、关闭
- out.flush();
- out.close();
- InputStream is = conn.getInputStream();
- try {
- if (is != null) {
- ByteArrayOutputStream outStream = new ByteArrayOutputStream();
- byte[] buffer = new byte[1024];
- int len = 0;
- while ((len = is.read(buffer)) != -1) {
- outStream.write(buffer, 0, len);
- }
- // is.close();
- ret = outStream.toByteArray();
- }
- } catch (Exception e) {
- e.printStackTrace();
- } finally {
- if (null != is) {
- is.close();
- }
- }
- } catch (Exception e) {
- e.printStackTrace();
- }
- return ret;
- }
- public static byte[] get(String url, String content, String charset)
- throws NoSuchAlgorithmException, KeyManagementException,
- IOException {
- byte[] ret = null;
- try {
- SSLContext sc = SSLContext.getInstance("SSL");
- sc.init(null, new TrustManager[] { new TrustAnyTrustManager() },
- new java.security.SecureRandom());
- URL console = new URL(url);
- HttpsURLConnection conn = (HttpsURLConnection) console
- .openConnection();
- conn.setRequestMethod("GET");
- // conn.setRequestProperty("Content-type",
- // "multipart/form-data;boundary=*****");
- // 在与服务器连接之前,设置一些网络参数
- conn.setConnectTimeout(10000);
- conn.setReadTimeout(10000);
- // conn.setDoOutput(true);
- conn.setSSLSocketFactory(sc.getSocketFactory());
- conn.setHostnameVerifier(new TrustAnyHostnameVerifier());
- conn.setRequestProperty("Connection", "Keep-Alive");
- conn.setRequestProperty("Charset", "UTF-8");
- conn.setRequestProperty("Content-Type",
- "application/x-www-form-urlencoded");
- conn.connect();
- InputStream is = conn.getInputStream();
- try {
- if (is != null) {
- ByteArrayOutputStream outStream = new ByteArrayOutputStream();
- byte[] buffer = new byte[1024];
- int len = 0;
- while ((len = is.read(buffer)) != -1) {
- outStream.write(buffer, 0, len);
- }
- ret = outStream.toByteArray();
- }
- } catch (Exception e) {
- e.printStackTrace();
- } finally {
- if (null != is) {
- is.close();
- }
- }
- } catch (Exception e) {
- e.printStackTrace();
- }
- // 关闭输入流
- return ret;
- }
- private static class TrustAnyTrustManager implements X509TrustManager {
- TrustAnyTrustManager() {
- // 这里可以进行证书的初始化操作
- }
- public void checkClientTrusted(X509Certificate[] chain, String authType)
- throws CertificateException {
- // System.out.println("检查客户端的可信任状态...");
- }
- public void checkServerTrusted(X509Certificate[] chain, String authType)
- throws CertificateException {
- // System.out.println("检查服务器的可信任状态");
- }
- public X509Certificate[] getAcceptedIssuers() {
- // System.out.println("获取接受的发行商数组...");
- return new X509Certificate[] {};
- }
- }
- private static class TrustAnyHostnameVerifier implements HostnameVerifier {
- public boolean verify(String hostname, SSLSession session) {
- return true;
- }
- }
- }
CipherMain.java
- package com.test.CipherIndex;
- import java.io.IOException;
- import java.io.UnsupportedEncodingException;
- import java.security.KeyManagementException;
- import java.security.NoSuchAlgorithmException;
- import com.test.MainTest;
- public class CipherMain {
- public static void main(String[] args) {
- CipherMain cm = new CipherMain();
- // cm.test_post();
- cm.test_get();
- }
- void test_post() {
- SocketReq socketreq = new SocketReq();
- try {
- byte[] getret = socketreq.get(
- "https://192.168.111.30/Mycloud/index.html", "1", "utf-8");
- String getstrRead = new String(getret, "utf-8");
- System.out.println(getstrRead);
- } catch (KeyManagementException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } catch (NoSuchAlgorithmException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- catch (UnsupportedEncodingException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- void test_get() {
- SocketReq socketreq = new SocketReq();
- try {
- byte[] ret = socketreq.post(
- "https://192.168.111.30/Mycloud/index.html", "1", "utf-8");
- String strRead = new String(ret, "utf-8");
- System.out.println(strRead);
- } catch (KeyManagementException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } catch (NoSuchAlgorithmException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- catch (UnsupportedEncodingException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- }
http://blog.csdn.net/bupt073114/article/details/52092489
一言不合就写socket的post和get请求(拼内容,然后发出去即可)的更多相关文章
- 一言不合就动手系列篇一-仿电商平台前端搜索插件(filterMore)
话说某年某月某日,后台系统需要重构,当时公司还没有专业前端,由我负责前台页面框架搭建,做过后台系统的都知道,传统的管理系统大部分都是列表界面和编辑界面.列表界面又由表格和搜索框组成, 对于全部都是输入 ...
- 在windows下用C语言写socket通讯实例
原文:在windows下用C语言写socket通讯实例 From:Microsoft Dev Center #undef UNICODE #define WIN32_LEAN_AND_MEAN #in ...
- C++写Socket——TCP篇(0)建立连接及双方传输数据
满山的红叶--飘落之时-- 最近接触了点关于用C++写socket的东西,这里总结下. 这里主要是关于TCP的,TCP的特点什么的相关介绍在我另一篇博文里,所以这里直接动手吧. 我们先在windows ...
- php 利用socket发送GET,POST请求
作为php程序员一定会接触http协议,也只有深入了解http协议,编程水平才会更进一步.最近我一直在学习php的关于http的编程,许多东西恍然大悟,受益匪浅.希望分享给大家.本文需要有一定http ...
- HTTP 笔记与总结(3 )socket 编程:发送 GET 请求
使用 PHP + socket 模拟发送 HTTP GET 请求,过程是: ① 打开连接 ② 构造 GET 请求的数据:写入请求行.请求头信息.请求主体信息(GET 请求没有主体信息) ③ 发送 GE ...
- 『言善信』Fiddler工具 — 2、HTTP请求内容详解
目录 1.HTTP协议介绍 2.使用Fiddler抓取一个请求 3.НТТP请求报文 (1)НТТP请求报文说明 (2)请求行 (3)请求头(Request Header) (4)请求体 4.НТТР ...
- 用PYTHON硬写SOCKET
这个文章的系列很有意思,练练~~: http://python.jobbole.com/82763/ :) 第一步,最简单的SERVER和CLIENT.感觉和写JAVA,C的最简单的一样一样的,,看来 ...
- [Golang] 从零开始写Socket Server(1): Socket-Client框架
版权声明:本文为博主原创文章,未经博主允许不得转载. 第一次跑到互联网公司实习 ..感觉自己进步飞快啊~第一周刚写了个HTTP服务器用于微信公共号的点餐系统~ 第二周就直接开始一边自学Go语言一边写用 ...
- Python3.6写socket程序
Python进行Socket程序编写使用的主要模块就是 socket 模块,在这个模块中可以找到 socket()函数,该函数用于创建套接字对象.套接字也有自己的方法集,这些方法可以实现基于套接字的网 ...
随机推荐
- 【BZOJ 3172】单词
[链接]h在这里写链接 [题意] 给你n个单词; 这n个单词组成了一篇文章; 问你每个单词在这篇文章中出现了多少次. 其中每个单词之间用一个逗号隔开->组成一篇文 ...
- ios移动旋转缩放动画
//移动旋转动画效果 CATransform3D rotate = CATransform3DMakeRotation(70.0 * M_PI / 180.0, 0.0, 0.0, 1.0); CAT ...
- ios 不支持屏幕旋转
- (NSUInteger)supportedInterfaceOrientations { return UIInterfaceOrientationMaskPortrait; }
- Android利用AlarmManager执行定时任务
Android中的AlarmManager功能很强大,它是一个全局定时器,可以在指定时间或者指定周期启动其他组件(包括Activity.Service.BroadcastReceiver). 使用Al ...
- JAVA初始开发环境搭建
上午想在一台新电脑上搭建java开发环境,在没有之前备份的情况下,单靠网络还真有点麻烦.最主要的原因是貌似在我当前的网络环境下jdk无法下载,官网这个链接半天打不开,http://www.oracle ...
- Java 开源博客——B3log Solo 0.6.7 正式版发布了!
Java 开源博客 -- B3log Solo 0.6.7 正式版发布了!欢迎大家下载. 另外,欢迎观摩 B3log 团队的新项目:Wide,也非常欢迎大家参与进来 :-) 特性 基于标签的文章分类 ...
- HDU 1425 sort hash+加速输入
http://acm.hdu.edu.cn/showproblem.php?pid=1425 题目大意: 给你n个整数,请按从大到小的顺序输出其中前m大的数. 其中n和m都是位于[-500000,50 ...
- Python数据结构之树
二叉树 嵌套列表方式 # coding:utf-8 # 列表嵌套法 def BinaryTree(r): return [r, [], []] def insertLeft(root, newBran ...
- php修改SESSION的有效生存时间
如何修改SESSION的生存时间 我们来手动设置 Session 的生存期: <?phpsession_start(); // 保存一天 $lifeTime = 24 * 3600; setco ...
- 【29.70%】【codeforces 723D】Lakes in Berland
time limit per test2 seconds memory limit per test256 megabytes inputstandard input outputstandard o ...