zoukankan      html  css  js  c++  java
  • webservice 接口通过 HTTP 获取数据

     1 using System;
     2 using System.Collections.Generic;
     3 using System.Linq;
     4 using System.Web;
     5 using System.Net;
     6 using System.Text;
     7 using System.IO;
     8 
     9 namespace testRsa
    10 {
    11 public class GetDataByHttp
    12 {
    13 
    14 
    15 public static string DoPost(string url, string data)
    16 {
    17 HttpWebRequest req = GetWebRequest(url, "POST");
    18 byte[] postData = Encoding.UTF8.GetBytes(data);
    19 Stream reqStream = req.GetRequestStream();
    20 reqStream.Write(postData, 0, postData.Length);
    21 reqStream.Close();
    22 HttpWebResponse rsp = (HttpWebResponse)req.GetResponse();
    23 Encoding encoding = Encoding.GetEncoding(rsp.CharacterSet);
    24 return GetResponseAsString(rsp, encoding);
    25 }
    26 
    27 public static HttpWebRequest GetWebRequest(string url, string method)
    28 {
    29 HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
    30 req.ServicePoint.Expect100Continue = false;
    31 req.ContentType = "application/x-www-form-urlencoded;charset=utf-8";
    32 req.ContentType = "text/json";
    33 req.Method = method;
    34 req.KeepAlive = true;
    35 req.UserAgent = "guanyisoft";
    36 req.Timeout = 1000000;
    37 req.Proxy = null;
    38 return req;
    39 }
    40 
    41 public static string GetResponseAsString(HttpWebResponse rsp, Encoding encoding)
    42 {
    43 StringBuilder result = new StringBuilder();
    44 Stream stream = null;
    45 StreamReader reader = null;
    46 try
    47 {
    48 // 以字符流的方式读取HTTP响应
    49 stream = rsp.GetResponseStream();
    50 reader = new StreamReader(stream, encoding);
    51 // 每次读取不大于256个字符,并写入字符串
    52 char[] buffer = new char[256];
    53 int readBytes = 0;
    54 while ((readBytes = reader.Read(buffer, 0, buffer.Length)) > 0)
    55 {
    56 result.Append(buffer, 0, readBytes);
    57 }
    58 }
    59 finally
    60 {
    61 // 释放资源
    62 if (reader != null) reader.Close();
    63 if (stream != null) stream.Close();
    64 if (rsp != null) rsp.Close();
    65 }
    66 
    67 return result.ToString();
    68 }
    69 
    70 
    71 
    72 }
    73 }
    74   
    View Code
  • 相关阅读:
    eclipse安装Genymotion插件
    [Eclipse插件] 安装和使用JD-Eclipse插件
    [Eclipse插件] Eclipse中如何安装和使用GrepCode插件
    [Android Studio] Android Studio如何删除module(转载)
    前端html基本标签
    python实现简单FTP
    文件的md5计算
    suprocess模块
    几个小例子
    configparser模块
  • 原文地址:https://www.cnblogs.com/kgdjgd/p/5853871.html
Copyright © 2011-2022 走看看