socket,获取html,webservice等,支持chunked,gzip,deflate
1. [代码][C#]代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Net;
using System.IO;
using System.IO.Compression;
using System.Reflection;
namespace ConsoleApplication1
{
internal class user
{
public string content { get; set; }
public string mdpass { get; set; }
public string mobile { get; set; }
public string name { get; set; }
public string pass { get; set; }
public string ptimestamp { get; set; }
public string sendPort { get; set; }
public string sendTime { get; set; }
public string title { get; set; }
}
class Program
{
static void Main(string[] args)
{
Console.WriteLine("********WebService Testing!*******");
HttpHelper http = new HttpHelper();
Dictionary<string, string> dics = new Dictionary<string, string>();
user bean = new user();
bean.name = "122";
bean.pass = "21";
bean.ptimestamp = "20121109111950";
bean.content = "测试";
bean.mobile = "13432033335";
bean.sendPort = "";
bean.sendTime = "";
bean.mdpass = "4CC4122226B23F75EDE78";
http.NameSpace = "http://*.*.*.*:8080//sms";
http.WEncoding = Encoding.UTF8;
Console.WriteLine(http.GetWebServiceStr("http://124.****:8080//sms",
"SendSMS", http.CreateSoap(bean)));
Console.WriteLine("*********Get Testing!***********");
http.WEncoding = Encoding.UTF8;
http.IniStalling();
Console.WriteLine(http.MethodGetHttpStr("http://*.*.*.*:8080/smshttp?"));
Console.WriteLine("*********Post Testing!**********");
http.WEncoding = Encoding.UTF8;
http.IniStalling();
Console.WriteLine(http.MethodPostHttpStr("http://*.*.*.*:8080/smshttp?act=getbalance", ""));
Console.ReadLine();
}
}
/// <summary>
/// socket核心
/// </summary>
internal class HttpHelper
{
public HttpHelper()
{
IniStalling();
}
public void IniStalling()
{
HttpHeaders = new List<HttpHeaderModel>();
ResponseHttpHeaders = new List<HttpHeaderModel>();
DicCookies = new List<CookiesModel>();
AddHttpHeader("Accept", "*/*");
AddHttpHeader("Accept-Language", "zh-CN");
AddHttpHeader("User-Agent", "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Win64; x64; Trident/5.0)");
AddHttpHeader("UA-CPU", "AMD64");
AddHttpHeader("Connection", "Keep-Alive");
}
public Encoding WEncoding = Encoding.UTF8;
/// <summary>
/// 请求或者返回的头文件
/// </summary>
internal class HttpHeaderModel
{
public string Key { get; set; }
public string Value { get; set; }
}
/// <summary>
/// get,post的cookies
/// </summary>
internal class CookiesModel
{
public string Key { get; set; }
public string Value { get; set; }
public string Domain { get; set; }
}
internal List<HttpHeaderModel> HttpHeaders = new List<HttpHeaderModel>();
internal List<HttpHeaderModel> ResponseHttpHeaders = new List<HttpHeaderModel>();
internal List<CookiesModel> DicCookies = new List<CookiesModel>();
/// <summary>
/// 添加HTTP头
/// </summary>
/// <param name="key"></param>
/// <param name="value"></param>
public void AddHttpHeader(string key, string value)
{
foreach (HttpHeaderModel httpHeaderModel in HttpHeaders)
{
if (httpHeaderModel.Key == key)
{
httpHeaderModel.Value = value;
return;
}
}
HttpHeaders.Add(new HttpHeaderModel()
{
Key = key,
Value = value
});
}
public string MethodGetHttpStr(string url)
{
return GetHttpByte(url, null);
}
public string MethodPostHttpStr(string url, string data)
{
return GetHttpByte(url, data);
}
/// <summary>
/// 设置命名空间,请在地址后面加上wsdl获取。
/// </summary>
public string NameSpace { get; set; }
private int index = 0;
public string CreateSoap(object obj)
{
StringBuilder sb = new StringBuilder();
Type tType = obj.GetType();
PropertyInfo[] pInfos = tType.GetProperties();
sb.AppendLine("<test" + index + " xsi:type=\"m" + index + ":" + tType.Name + "\">");
foreach (PropertyInfo pInfo in pInfos)
{
sb.AppendLine(string.Format(" <{0}>{1}</{0}>", pInfo.Name, pInfo.GetValue(obj, null)));
}
sb.AppendLine("</test" + index + ">");
index++;
return sb.ToString();
}
public string CreateSoap(Dictionary<string, string> MethodParms)
{
StringBuilder sb = new StringBuilder();
foreach (KeyValuePair<string, string> keyValuePair in MethodParms)
{
sb.AppendLine(string.Format(" <{0}>{1}</{0}>", keyValuePair.Key, keyValuePair.Value));
}
return sb.ToString();
}
public string GetWebServiceStr(string url, string MethodName, string soap)
{
index = 0;
if (string.IsNullOrEmpty(NameSpace))
throw new MissingFieldException("请输入NameSpace");
if (url.Contains("asmx"))
AddHttpHeader("SOAPAction", "\"" + NameSpace.TrimEnd('/') + "/" + MethodName + "\"");
else
AddHttpHeader("SOAPAction", "\"\"");
AddHttpHeader("Content-Type", "text/xml; charset=utf-8");
StringBuilder sb = new StringBuilder();
sb.AppendLine("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
sb.AppendLine("<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">");
sb.AppendLine("<soap:Body>");
sb.AppendLine(string.Format("<" + MethodName + " xmlns=\"" + NameSpace + "\">"));
sb.Append(soap);
sb.AppendLine(string.Format("</" + MethodName + ">"));
sb.AppendLine("</soap:Body>");
sb.AppendLine("</soap:Envelope>");
return MethodPostHttpStr(url, sb.ToString());
}
public string GetHttpByte(string url, string data = "")
{
bool methodPost = !string.IsNullOrEmpty(data);
if (methodPost)
{
byte[] sendBytes = WEncoding.GetBytes(data);
AddHttpHeader("Content-Length", sendBytes.Length.ToString());
}
string cookies =
DicCookies.Aggregate(string.Empty,
(current, cookie) => current + string.Format("{0}:{1};", cookie.Key, cookie.Value));
string[] urlspils = url.Replace("http://", "").Split('/');
string host = urlspils[0];
string methodurl = url.Replace("http://", "").Remove(0, host.Length);
string[] ipport = host.Split(':');
string ip = "127.0.0.1";
string post = "80";
if (ipport.Length > 1)
{
host = ipport[0];
post = ipport[1];
}
IPAddress[] addressList = Dns.GetHostAddresses(host);
if (addressList.Length > 0)
{
ip = addressList[0].ToString();
}
Socket httpSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPEndPoint serverHost = new IPEndPoint(IPAddress.Parse(ip), int.Parse(post));
StringBuilder httpHeader = new StringBuilder();
httpHeader.Append((methodPost ? "POST" : "GET") + " " + methodurl + " HTTP/1.1\r\n");
AddHttpHeader("Host", host);
if (!string.IsNullOrEmpty(cookies))
AddHttpHeader("Cookie", cookies);
foreach (var item in HttpHeaders)
{http://www.huiyi8.com/hunsha/lifu/
httpHeader.Append(string.Format("{0}: {1}\r\n", item.Key, item.Value));
}婚纱礼服欣赏
string httpData = string.Format("{0}\r\n{1}", httpHeader, data);
Console.WriteLine(httpData);
try
{
httpSocket.Connect(serverHost);
if (!httpSocket.Connected)
throw new WebException("连接不上服务器");
byte[] bytesSend = WEncoding.GetBytes(httpData);
#region Socket
//httpSocket.Send(bytesSend);
//byte[] bytesReceive = new byte[8192];
//string getresult = string.Empty;
//while (true)
//{
// int receiveLen = httpSocket.Receive(bytesReceive, bytesReceive.Length, SocketFlags.None);
// getresult += WEncoding.GetString(bytesReceive, 0, receiveLen);
// if ((receiveLen) == 0 || receiveLen < bytesReceive.Length)
// break;
// Thread.Sleep(10);
//}
//return getresult;
#endregion
#region networkstrem
using (var stream = new NetworkStream(httpSocket))
{
stream.Write(bytesSend, 0, bytesSend.Length);
while (true)
{
var line = ReadLine(stream);
if (line.Length == 0)
break;
if (line.Contains("HTTP/1.1"))
continue;
int index = line.IndexOf(':');
ResponseHttpHeaders.Add(new HttpHeaderModel()
{
Key = line.Substring(0, index),
Value = line.Substring(index + 2)
});
}
Stream responseStream = stream;
bool ischunked = GetFromResponseHeader("Transfer-Encoding").Count == 1;
List<string> conlengt = GetFromResponseHeader("Content-Length");
long contentlenght = 0;
if (conlengt.Count > 0)
contentlenght = long.Parse(conlengt[0]);
List<string> contentEncodings = GetFromResponseHeader("Content-Encoding");
if (contentEncodings.Count == 1)
{
if (contentEncodings[0].Equals("gzip"))
{
responseStream = new GZipStream(responseStream, CompressionMode.Decompress);
}
else if (contentEncodings[0].Equals("deflate"))
{
responseStream = new DeflateStream(responseStream, CompressionMode.Decompress);
}
}
if (ischunked)
{
StringBuilder sbReadstr = new StringBuilder();
// var respBuffer = new byte[contentlenght + 1024];
int readlinecount = 1;
while (true)
{
var line = ReadLine(responseStream);
int lenght = 0;
if (readlinecount % 2 == 0)
{
sbReadstr.AppendLine(line);
}
else if (line.Length == 1 && int.TryParse(line, out lenght) && readlinecount % 2 == 1 && readlinecount != 1)
{
if (lenght == 0)
break;
}
readlinecount++;
}
//var strbytes = WEncoding.GetBytes(sbReadstr.ToString());
//memStream.Write(strbytes, 0, strbytes.Length);
return sbReadstr.ToString();
}
else
{
var respBuffer = new byte[contentlenght + 1024];
try
{
int bytesRead = responseStream.Read(respBuffer, 0, respBuffer.Length);
{
return WEncoding.GetString(respBuffer, 0, bytesRead);
}
}
finally
{
responseStream.Close();
}
}
}
#endregion
}
catch (Exception ex)
{
throw ex;
}
finally
{
if (httpSocket.Connected)
httpSocket.Close();
}
}
public List<string> GetFromResponseHeader(string key)
{
return (from item in ResponseHttpHeaders where item.Key == key select item.Value).ToList();
}
string ReadLine(Stream stream)
{
var lineBuffer = new List<byte>();
while (true)
{
int b = stream.ReadByte();
if (b == -1)
{
return null;
}
if (b == 10)
{
break;
}
if (b != 13)
{
lineBuffer.Add((byte)b);
}
}
return WEncoding.GetString(lineBuffer.ToArray());
}
}
internal class httpNetHelper
{
public string CreateGetString(string geturl)
{
return GetHtml(geturl);
}
public string CreatePostString(string posturl, string date)
{
return GetHtml(posturl, Encoding.UTF8.GetBytes(date));
}
private String userAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Trident/4.0; .NET CLR 2.0.50727; .NET CLR 3.0.04506.30; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729; .NET CLR 1.1.4322; .NET4.0C; .NET4.0E)";
private String accept = "*/*";
public String contentType = "application/x-www-form-urlencoded; charset=UTF-8";
/// <summary>
/// 从响应获得字符串
/// </summary>
/// <param name="url"></param>
/// <param name="data"></param>
/// <returns></returns>
internal string GetHtml(string url, byte[] data = null)
{
using (var response = GetResponse(url, data))
{
using (var stream = response.GetResponseStream())
{
using (var sr = new StreamReader(stream, Encoding.UTF8))
{
return sr.ReadToEnd();
}
}
}
}
internal HttpWebResponse GetResponse(string url, byte[] data = null)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.ContentType = "application/x-www-form-urlencoded; charset=UTF-8";
request.UserAgent = userAgent;
request.Accept = accept;
if (data != null)
{
request.Method = "POST";
request.ContentLength = data.Length;
using (var stream = request.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
}
else
{
request.Method = "GET";
}
request.Timeout = 5000;
return (HttpWebResponse)request.GetResponse();
}
}
}
socket,获取html,webservice等,支持chunked,gzip,deflate的更多相关文章
- android 通过socket获取IP
如题<android 通过socket获取IP>: socket.getInetAddress().getHostAddress();
- Java之利用Socket获取网站内容
public void main(String[] args){ String host = "123.126.113.42"; int port = 80; Socket s = ...
- 使用SOCKET获取网页的内容
使用fsockopen()函数来实现获取页面信息,完整代码如下 //设置字符集(由于要抓取的网易网站字符集编码是gbk编码) header("content-type:text/html;c ...
- WebClient 支持 gzip, deflate
低调偷偷的下别人数据 发现下出来乱码- 用F12看看请求,原来人家是用了gzip压缩的- 试着自己加个Heading wc.Headers.Add("Accept-Encoding" ...
- 从python爬虫引发出的gzip,deflate,sdch,br压缩算法分析
今天在使用python爬虫时遇到一个奇怪的问题,使用的是自带的urllib库,在解析网页时获取到的为b'\x1f\x8b\x08\x00\x00\x00\x00...等十六进制数字,尝试使用chard ...
- httpclient访问网站时设置Accept-Encoding为gzip,deflate返回的结果为乱码的问题
近期迷恋上httpclient模拟各种网站登陆,浏览器中的开发者工具中查看请求头信息,然后照葫芦画瓢写到httpclient的请求中去,requestheader中有这么一段设置: Accept-En ...
- 笔记:服务器压缩方案 来源于 Accept-Encoding: gzip, deflate 问题
笔记:服务器压缩方案 来源于 Accept-Encoding: gzip, deflate 问题 事情起因:odoo demo 没有启动web 压缩 目前流行的 web 压缩技术 gzip br 支持 ...
- 【转】如何在Windows+VS2005使用最新静态libcurl 7.35.0获取网页数据,支持HTTPS
地址: http://blog.csdn.net/hujkay作者:Jekkay Hu(34538980@qq.com)关键词:Windows,curl,ssl, visual c++ 2005, ...
- C语言之socket获取网页源码
写爬虫也许你用的是python,类似urlopen(url).read()即可获得普通的网页的源码,或者用的java的网络库加上流操作,或者其他高级语言.但你有没有想过使用C语言来实现呢?我曾经以为用 ...
随机推荐
- 《转》 在C++中使用TinyXML2解析xml
读取和设置xml配置文件是最经常使用的操作,试用了几个C++的XML解析器,个人感觉TinyXML是使用起来最舒服的,由于它的API接口和Java的十分类似.面向对象性非常好. TinyX ...
- 环信ONE SDK架构介绍
环信ONE SDK架构介绍 摘要 环信即时通讯SDK自2014年6月正式公布2.0版本号至今已走过一个年头.从主要的单聊功能,到群聊功能,再到聊天室的实现.SDK无论是功能.稳定性,还是易集成性都在一 ...
- IE对CSS样式的数量和大小的限制
项目中遇到的问题,css写的样式无法渲染,各种百度后发现大概是这个原因: IE对CSS样式的数量和大小的限制 文档中只有前31个link或style标记关联的CSS能够应用. 从第32个开始,其标记关 ...
- shell脚本实现定时重启任务并输出日志信息
#!/bin/bash #当前日期 time=`date` pidno=`ps aux|grep adserver-beta|grep -v "grep"|awk '{print ...
- 回到顶部totop
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title> ...
- Web前端开发--JS技术大梳理
什么是JS JavaScript是一种直译式脚本语言,是一种动态类型.弱类型.基于原型的语言,内置支持类型.它的解释器被称为JavaScript引擎,为浏览器的一部分,广泛用于客户端的脚本语 ...
- ThinkPHP中的模型命名
当我们创建一个UserModel类的时候,其实已经遵循了系统的约定.ThinkPHP要求数据库的表名和模型类的命名遵循一定的规范,首先数据库的表名和字段全部采用小写形式,模型类的命名规则是除去表前缀的 ...
- [水]ZOJ1201
给原排列 求 其前面有多少个数比他大. 给每一个数1...2..n前面有多少个数比他大,求原序列 第一个直接统计 第二个从1開始找出第inv[i]+1个空位置放进去就好 printf里的format ...
- 面试题 15:链表中倒数第 k 个结点
面试题 15:链表中倒数第 k 个结点 题目:输入一个链表,输出该链表中倒数第 k 个结点.为了符合大多数人的习惯, 本题从 1 开始计数,即链表的尾结点是倒数第一个结点.例如一个有 6 个结点的 链 ...
- 基于JQuery实现表单元素值的回写
form.jsp: <%@ page language="java" import="java.util.*" pageEncoding="GB ...