Skip to content

Instantly share code, notes, and snippets.

@mechiland
Created March 27, 2014 05:36
Show Gist options
  • Save mechiland/9801017 to your computer and use it in GitHub Desktop.
Save mechiland/9801017 to your computer and use it in GitHub Desktop.
Jinshuju API Push for C#
<%@ WebHandler Language="C#" Class="JinshujuHandler" %>
using System;
using System.Web;
using System.Text;
using System.IO;
using Newtonsoft.Json.Linq;//引用第三方控件Newtonsoft.Json.dll
/*
*Company:QingDao Transinfo
*Author: Andy.Sun
*CreateDate:2014-03-27
*/
public class JinshujuHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
GetPostData(context);
}
/// <summary>
/// 获取金数据接口,并写入一个txt文件
/// </summary>
/// <param name="context"></param>
public void GetPostData(HttpContext context)
{
if ( context.Request.RequestType.ToUpper() == "POST")
{
System.IO.Stream s = context.Request.InputStream;
try
{
int nlen = (int)s.Length;
byte[] buffer = new byte[nlen];
s.Read(buffer, 0, nlen);
StringBuilder builder = new StringBuilder();
//builder.Append(Encoding.UTF8.GetString(buffer));
dynamic obj = JObject.Parse(Encoding.UTF8.GetString(buffer));
builder.Append(obj);//完整的json字符串
/*使用json字符串中的字段*/
string strForm = obj.form;//表单名称
builder.Append(strForm);
string str = obj.entry.field_7;//单值字段
builder.Append(str);
JArray str2 = obj.entry.field_20;//多值字段
foreach (string str3 in str2)
{
builder.Append(str3);
}
string strPath = context.Server.MapPath("test.txt");
FileStream fs = new FileStream(strPath, FileMode.Create);
//获得字节数组
byte[] data = new UTF8Encoding().GetBytes(builder.ToString());
//开始写入
fs.Write(data, 0, data.Length);
//清空缓冲区、关闭流
fs.Flush();
fs.Close();
}
catch (Exception ex)
{
throw ex;
}
finally
{
s.Close();
}
}
}
public bool IsReusable
{
get
{
return false;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment