1. 程式人生 > >C# 後臺傳送各種http請求

C# 後臺傳送各種http請求

程式碼:

using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;

namespace SXYC.Common
{
    public class HttpClientHelpClass
    {
        /// <summary>
        /// get請求
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public static string GetResponse(string url, out string statusCode)
        {
            if (url.StartsWith("https"))
                System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;

            var httpClient = new HttpClient();
            httpClient.DefaultRequestHeaders.Accept.Add(
              new MediaTypeWithQualityHeaderValue("application/json"));
            HttpResponseMessage response = httpClient.GetAsync(url).Result;
            statusCode = response.StatusCode.ToString();
            if (response.IsSuccessStatusCode)
            {
                string result = response.Content.ReadAsStringAsync().Result;
                return result;
            }
            return null;
        }

        public static string RestfulGet(string url)
        {
            HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
            // Get response
            using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
            {
                // Get the response stream
                StreamReader reader = new StreamReader(response.GetResponseStream());
                // Console application output
                return reader.ReadToEnd();
            }
        }

        public static T GetResponse<T>(string url)
           where T : class, new()
        {
            if (url.StartsWith("https"))
                System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;

            var httpClient = new HttpClient();
            httpClient.DefaultRequestHeaders.Accept.Add(
               new MediaTypeWithQualityHeaderValue("application/json"));
            HttpResponseMessage response = httpClient.GetAsync(url).Result;

            T result = default(T);

            if (response.IsSuccessStatusCode)
            {
                Task<string> t = response.Content.ReadAsStringAsync();
                string s = t.Result;

                result = JsonConvert.DeserializeObject<T>(s);
            }
            return result;
        }

        /// <summary>
        /// post請求
        /// </summary>
        /// <param name="url"></param>
        /// <param name="postData">post資料</param>
        /// <returns></returns>
        public static string PostResponse(string url, string postData, out string statusCode)
        {
            if (url.StartsWith("https"))
                System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;

            HttpContent httpContent = new StringContent(postData);
            httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
            httpContent.Headers.ContentType.CharSet = "utf-8";

            HttpClient httpClient = new HttpClient();
            //httpClient..setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "utf-8");

            HttpResponseMessage response = httpClient.PostAsync(url, httpContent).Result;

            statusCode = response.StatusCode.ToString();
            if (response.IsSuccessStatusCode)
            {
                string result = response.Content.ReadAsStringAsync().Result;
                return result;
            }

            return null;
        }

        /// <summary>
        /// 發起post請求
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="url">url</param>
        /// <param name="postData">post資料</param>
        /// <returns></returns>
        public static T PostResponse<T>(string url, string postData)
            where T : class, new()
        {
            if (url.StartsWith("https"))
                System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;

            HttpContent httpContent = new StringContent(postData);
            httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
            HttpClient httpClient = new HttpClient();

            T result = default(T);

            HttpResponseMessage response = httpClient.PostAsync(url, httpContent).Result;

            if (response.IsSuccessStatusCode)
            {
                Task<string> t = response.Content.ReadAsStringAsync();
                string s = t.Result;

                result = JsonConvert.DeserializeObject<T>(s);
            }
            return result;
        }


        /// <summary>
        /// 反序列化Xml
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="xmlString"></param>
        /// <returns></returns>
        public static T XmlDeserialize<T>(string xmlString)
            where T : class, new()
        {
            try
            {
                XmlSerializer ser = new XmlSerializer(typeof(T));
                using (StringReader reader = new StringReader(xmlString))
                {
                    return (T)ser.Deserialize(reader);
                }
            }
            catch (Exception ex)
            {
                throw new Exception("XmlDeserialize發生異常:xmlString:" + xmlString + "異常資訊:" + ex.Message);
            }

        }

        public static string PostResponse(string url, string postData, string token, string appId, string serviceURL, out string statusCode)
        {
            if (url.StartsWith("https"))
                System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;

            HttpContent httpContent = new StringContent(postData);
            httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
            httpContent.Headers.ContentType.CharSet = "utf-8";

            httpContent.Headers.Add("token", token);
            httpContent.Headers.Add("appId", appId);
            httpContent.Headers.Add("serviceURL", serviceURL);


            HttpClient httpClient = new HttpClient();
            //httpClient..setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "utf-8");

            HttpResponseMessage response = httpClient.PostAsync(url, httpContent).Result;

            statusCode = response.StatusCode.ToString();
            if (response.IsSuccessStatusCode)
            {
                string result = response.Content.ReadAsStringAsync().Result;
                return result;
            }

            return null;
        }

        /// <summary>
        /// 修改API
        /// </summary>
        /// <param name="url"></param>
        /// <param name="postData"></param>
        /// <returns></returns>
        public static string KongPatchResponse(string url, string postData)
        {
            var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
            httpWebRequest.ContentType = "application/x-www-form-urlencoded";
            httpWebRequest.Method = "PATCH";

            byte[] btBodys = Encoding.UTF8.GetBytes(postData);
            httpWebRequest.ContentLength = btBodys.Length;
            httpWebRequest.GetRequestStream().Write(btBodys, 0, btBodys.Length);

            HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
            var streamReader = new StreamReader(httpWebResponse.GetResponseStream());
            string responseContent = streamReader.ReadToEnd();

            httpWebResponse.Close();
            streamReader.Close();
            httpWebRequest.Abort();
            httpWebResponse.Close();

            return responseContent;
        }

        /// <summary>
        /// 建立API
        /// </summary>
        /// <param name="url"></param>
        /// <param name="postData"></param>
        /// <returns></returns>
        public static string KongAddResponse(string url, string postData)
        {
            if (url.StartsWith("https"))
                ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;
            HttpContent httpContent = new StringContent(postData);
            httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded") { CharSet = "utf-8" };
            var httpClient = new HttpClient();
            HttpResponseMessage response = httpClient.PostAsync(url, httpContent).Result;
            if (response.IsSuccessStatusCode)
            {
                string result = response.Content.ReadAsStringAsync().Result;
                return result;
            }
            return null;
        }

        /// <summary>
        /// 刪除API
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public static bool KongDeleteResponse(string url)
        {
            if (url.StartsWith("https"))
                ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;

            var httpClient = new HttpClient();
            HttpResponseMessage response = httpClient.DeleteAsync(url).Result;
            return response.IsSuccessStatusCode;
        }

        /// <summary>
        /// 修改或者更改API        
        /// </summary>
        /// <param name="url"></param>
        /// <param name="postData"></param>
        /// <returns></returns>
        public static string KongPutResponse(string url, string postData)
        {
            if (url.StartsWith("https"))
                ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;

            HttpContent httpContent = new StringContent(postData);
            httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded") { CharSet = "utf-8" };

            var httpClient = new HttpClient();
            HttpResponseMessage response = httpClient.PutAsync(url, httpContent).Result;
            if (response.IsSuccessStatusCode)
            {
                string result = response.Content.ReadAsStringAsync().Result;
                return result;
            }
            return null;
        }

        /// <summary>
        /// 檢索API
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public static string KongSerchResponse(string url)
        {
            if (url.StartsWith("https"))
                ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;

            var httpClient = new HttpClient();
            HttpResponseMessage response = httpClient.GetAsync(url).Result;
            if (response.IsSuccessStatusCode)
            {
                string result = response.Content.ReadAsStringAsync().Result;
                return result;
            }
            return null;
        }
    }
}

相關推薦

C# 後臺傳送各種http請求

程式碼:using Newtonsoft.Json; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using Sys

C# 後臺傳送http post請求

/// <summary>         /// 後臺傳送post請求         /// </summary>         /// <param name="url">請求地址</param>         ///

C#後臺傳送HTTP請求

HttpResponse 1.涵蓋POST,GET方法 using System; using System.Collections.Generic; using System.IO; using System.IO.Compression; usi

C#使用HttpWebRequest進行HTTP請求傳送和接收的一些小結。(新增修復.NET4.0以下關於cookie的bug)

2014.11.29 新增HTTPS處理和常用的getMid函式 直接貼程式碼: #region httpUtils private const string DefaultUserAgent = "Mozilla/5.0 (Windows NT 5.1

後臺發送http請求通用方法,包括get和post

util line 通用方法 返回 finall 6.0 val except ktr package com.examsafety.service.sh; import java.io.BufferedReader; import java.io.IOExceptio

C# 如何發送Http請求

quest string uget class nuget bin ken pos ict HttpSender是一個用來發送Http消息的輕量庫,使用非常簡單 使用 Nuget,搜索 HttpSender 就能找到 命名空間是HttpSender,類名是Sender 方法

全域性攔截各種http請求

http請求無非就是ajax、src、href、表單 function hookAJAX() { XMLHttpRequest.prototype.nativeOpen = XMLHttpRequest.prototype.open; var customizeOpen = func

iOS網路請求太頻繁 處理之前傳送http請求(取消)

搜尋功能在APP中非常的常見,搜尋功能伴隨的往往是實時搜尋結果,極大的方便了使用者的查詢與實時資料的更新,但是也有極大的問題,當我們搜尋框的文字改變的時候,就會進行網路請求,如果輸入特別快的時候,網路請求也會特頻繁,對伺服器的壓力也就更大。 解決方法:在進行新的網路請求的時

關於微信小程式後臺常用的http請求

import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.net

C++使用CHttpFile實現Http請求

C++實現http請求的程式碼,參照網上的修改了下在mfc中使用 1、HttpClient.h //////////////////////////////////// HttpClient.h #ifndef HTTPCLIENT_H #define HTTPCLIENT

關於簡訊傳送HTTP請求的那些事

public static boolean sendSmsActivateFriends(String mobile, String content, String type) { //簡訊傳送開關 if(UN_SMS_SWITCH.equals("1")){ HttpClient cli

全網最詳細的如何在谷歌瀏覽器里正確下載並安裝Postman【一款功能強大的網頁除錯與傳送網頁HTTP請求的Chrome外掛】(圖文詳解)

     不多說,直接上乾貨!     想必,玩過Java Web的你,肯定是對於http post和get等請求測試的過程記憶猶新吧。     Postman的安裝方法分好幾種,主要分為兩種安裝模式介紹:       (1)chrome瀏覽器postman 外掛安裝  【本

C語言實現的http請求

/*  * =====================================================================================  *  * Filename: RequestHttp.c  *  * Descripti

C# 後臺處理http請求

處理 IT 方式 span 亂碼 bottom AD bytearray ret using System.Collections.Generic;using System.Linq;using System.Text;using System.Net;using Syst

C#後臺向某個網站傳送Get或者Post請求

C#通過後臺進行想某個網站傳送Get或者POST請求。 這個沒有多少內容,就直接上程式碼了,下面的是GET請求: public string GetFunction(string order,string payType,string filePrice) {

Linux下用c語言實現傳送http請求 方式可以Get或者Post例程參考

[1].[程式碼] Linux下用c語言實現傳送http請求 方式可以Get或者Post 跳至 [1] ? 1 2

C# 模擬傳送請求到java後臺 java程式碼接收處理引數的問題

前段時間接到一個需求,對接一個C#寫的工具類,給我們的系統後臺上傳資料。 需求不難,很常見,於是為了方便。我就這樣寫了(java框架SSH): C#模擬請求的程式碼 public static void Main(string[] args) {

C# 後臺使用HttpWebRequest傳送POST請求幫助類

using System; using System.Collections.Generic; using System.IO; using System.Net; using System.Text; namespace Utils { public class RequestHel

Linux下用c語言實現傳送http請求

前言 在linux下,使用socket進行程式設計,需要到伺服器上進行獲取資料,伺服器使用的php程式設計,需要使用http的方式進行獲取資料。 程式碼 #include <stdio.h> #include <string.h&

C傳送http請求

之前用python編寫了傳送http請求的。非常非常方便。很多細節都已經被python內部處理了。這裡來說說C編寫的http請求: #include <stdio.h> #include <string.h> #include <sys/soc