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中使用GIT提交文件至本地
    Eclipse中使用GIT更新项目
    Eclipse使用Git检出项目
    JQuery选择器排除某元素实现js代码
    如何在使用layer.prompt在输入值为空的情况下点击确定继续执行逻辑?
    怎样验证layer.prompt输入的值为数值型???
    使用ECharts制作图形时,如何设置指定图形颜色?
    JS中通过LayUI的layer.prompt弹出文本输入层,多个按钮回调获取输入值
    MAVEN环境配置
    【Linux】Tomcat安装及端口配置
  • 原文地址:https://www.cnblogs.com/kgdjgd/p/5853871.html
Copyright © 2011-2022 走看看