GVKun编程网logo

<经验>使用HttpClient做Http请求(httpclient怎么用)

25

此处将为大家介绍关于<经验>使用HttpClient做Http请求的详细内容,并且为您解答有关httpclient怎么用的相关问题,此外,我们还将为您介绍关于AndroidHttpClie

此处将为大家介绍关于<经验>使用HttpClient做Http请求的详细内容,并且为您解答有关httpclient怎么用的相关问题,此外,我们还将为您介绍关于Android HttpClient,DefaultHttpClient,HttpPost、android – 使用HttpClient的HTTP请求太慢了?、Android 使用 httpClient 取消http请求的方法、C#爬虫基础之HttpClient获取HTTP请求与响应的有用信息。

本文目录一览:

<经验>使用HttpClient做Http请求(httpclient怎么用)

<经验>使用HttpClient做Http请求(httpclient怎么用)

package cn.com.wind.utils;

import cn.com.wind.exception.TranspondException;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.http.httpentity;
import org.apache.http.HttpStatus;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;

import org.apache.http.util.EntityUtils;


import java.io.*;
import java.nio.charset.StandardCharsets;

/**
 * @Author qymeng
 * @Date 2021/10/25
 * @Description 接口转发的工具类
 */
@Slf4j
public class TranspondUtils {

    /**
     * POST请求
     *
     * @param json 请求的json体
     * @param url  请求的URL地址
     */
    public static String doPost(String json, String url) {
        HttpClient httpClient = new HttpClient();
        // 设置http连接主机服务超时时间
        httpClient.gethttpconnectionManager().getParams().setConnectionTimeout(35000);
        PostMethod postMethod = new PostMethod(url);
        // 设置post请求超时
        postMethod.getParams().setParameter(HttpMethodParams.so_TIMEOUT, 60000);
        // 设置请求重试机制,默认重试次数:3次,参数设置为true,重试机制可用,false相反
        postMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, true));

        String result = null;
        try {
            RequestEntity entity = new StringRequestEntity(json, "application/json", "UTF-8");
            //请求头信息
            postMethod.setRequestHeader("Content-Type", "application/json");
            postMethod.setRequestEntity(entity);
            httpClient.executeMethod(postMethod);
            if (postMethod.getStatusCode() == HttpStatus.SC_OK) {
                // 获取响应输入流
                InputStream inStream = postMethod.getResponseBodyAsstream();
                BufferedReader reader = new BufferedReader(new InputStreamReader(inStream, StandardCharsets.UTF_8));
                StringBuilder strber = new StringBuilder();
                String line;
                while ((line = reader.readLine()) != null)
                    strber.append(line).append("\n");
                inStream.close();
                result = strber.toString();
            } else {
                throw new TranspondException("请求服务端失败,状态码不为200");
            }
        } catch (IOException e) {
            throw new TranspondException("请求服务端失败,地址为:" + url);
        } catch (IllegalStateException e) {
            throw new TranspondException("URL地址不正确,该地址为:" + url);
        } catch (Exception e) {
            throw new TranspondException("其他异常");
        }
        return result;
    }

    public static String doPost(JSONObject json, String url) {
        String s = JSON.toJSONString(json);
        return doPost(s, url);
    }

    public static String doPost(Object json, String url) {
        String s = JSON.toJSONString(json);
        return doPost(s, url);
    }

    /**
     * GET请求
     *
     * @param url 请求的URL地址
     */
    public static String doGet(String url) {
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse response = null;
        String result = "";
        try {
            // 通过址默认配置创建一个httpClient实例
            httpClient = HttpClients.createDefault();
            // 创建httpGet远程连接实例
            HttpGet httpGet = new HttpGet(url);
            // 设置配置请求参数
            RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(35000)// 连接主机服务超时时间
                    .setConnectionRequestTimeout(35000)// 请求超时时间
                    .setSocketTimeout(60000)// 数据读取超时时间
                    .build();
            // 为httpGet实例设置配置
            httpGet.setConfig(requestConfig);
            // 执行get请求得到返回对象
            response = httpClient.execute(httpGet);
            // 通过返回对象获取返回数据
            httpentity entity = response.getEntity();
            // 通过EntityUtils中的toString方法将结果转换为字符串
            result = EntityUtils.toString(entity);
//            log.info("请求服务器成功");
        } catch (IOException e) {
            throw new TranspondException("GET请求异常, URL为:" + url);
        } finally {
            // 关闭资源
            if (null != response) {
                try {
                    response.close();
                } catch (IOException e) {
                    throw new TranspondException("关闭CloseableHttpResponse时出现异常, URL为:" + url);
                }
            }
            if (null != httpClient) {
                try {
                    httpClient.close();
                } catch (IOException e) {
                    throw new TranspondException("关闭CloseableHttpClient时出现异常, URL为:" + url);
                }
            }
        }
        return result;
    }
    public static JSONObject doGetJson(String url) {
        return JSONObject.parSEObject(doGet(url));
    }

 }

 

总结

以上是小编为你收集整理的&lt;经验&gt;使用HttpClient做Http请求全部内容。

如果觉得小编网站内容还不错,欢迎将小编网站推荐给好友。

原文地址:https://www.cnblogs.com/aeimio/p/16178471.html

Android HttpClient,DefaultHttpClient,HttpPost

Android HttpClient,DefaultHttpClient,HttpPost

我如何将字符串数据( JSONObject.toString())发送到URL.我想在util类中编写一个静态方法来执行此操作.我希望方法签名如下

public static String postData(String url,String postData)抛出SomeCustomException

字符串url的格式应该是什么

返回String是来自服务器的响应,作为json数据的字符串表示.

编辑

目前的连接工具

package my.package;
import my.package.exceptions.CustomException;

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

import org.apache.http.httpentity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;


 public class ConnectionUtil {

 public static String postData(String url,String postData)
        throws CustomException {

    // Create a new HttpClient and Post Header
    InputStream is = null;
    StringBuilder sb = null;
    String result = "";
    HttpClient httpclient = new DefaultHttpClient();

HttpPost httppost = new HttpPost();
    httppost.setHeader("host",url);

    Log.v("ConnectionUtil","opening POST connection to URI = " + httppost.getURI() + " url = " + URLDecoder.decode(url));

    try {
        httppost.setEntity(new StringEntity(postData));

        // Execute HTTP Post Request
        HttpResponse response = httpclient.execute(httppost);
        httpentity entity = response.getEntity();
        is = entity.getContent();

    } catch (Exception e) {
        Log.e("log_tag","Error in http connection " + e.toString());
        e.printstacktrace();
        throw new CustomException("Could not establish network connection");
    }
    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                is,"utf-8"),8);
        sb = new StringBuilder();
        sb.append(reader.readLine() + "\n");
        String line = "0";

        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }

        is.close();
        result = sb.toString();

    } catch (Exception e) {
        Log.e("log_tag","Error converting result " + e.toString());
        throw new CustomException("Error parsing the response");
    }
    Log.v("ConnectionUtil","Sent: "+postData);
    Log.v("ConnectionUtil","Got result "+result);
    return result;

}

}

Logcat输出

10-16 11:27:27.287: E/log_tag(4935): Error in http connection java.lang.NullPointerException
10-16 11:27:27.287: W/System.err(4935): java.lang.NullPointerException
10-16 11:27:27.287: W/System.err(4935): at org.apache.http.impl.client.AbstractHttpClient.determineTarget(AbstractHttpClient.java:496)
10-16 11:27:27.307: W/System.err(4935): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
10-16 11:27:27.327: W/System.err(4935): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
10-16 11:27:27.327: W/System.err(4935): at in.gharpay.zap.integration.ConnectionUtil.postData(ConnectionUtil.java:92)
10-16 11:27:27.327: W/System.err(4935): at in.gharpay.zap.integration.ZapTransaction$1.doInBackground(ZapTransaction.java:54)
10-16 11:27:27.327: W/System.err(4935): at in.gharpay.zap.integration.ZapTransaction$1.doInBackground(ZapTransaction.java:1)
10-16 11:27:27.327: W/System.err(4935): at android.os.AsyncTask$2.call(AsyncTask.java:185)
10-16 11:27:27.327: W/System.err(4935): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:306)
10-16 11:27:27.327: W/System.err(4935): at java.util.concurrent.FutureTask.run(FutureTask.java:138)
10-16 11:27:27.327: W/System.err(4935): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1088)
10-16 11:27:27.327: W/System.err(4935): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:581)
10-16 11:27:27.327: W/System.err(4935): at java.lang.Thread.run(Thread.java:1019)
10-16 11:27:27.327: V/log_tag(4935): Could not establish network connection

解决方法

我认为在您的代码中,基本问题是由您使用StringEntity将参数POST到网址的方式引起的.检查以下代码是否有助于使用StringEntity将数据发布到服务器.
// Build the JSON object to pass parameters
    JSONObject jsonObj = new JSONObject();
    jsonObj.put("username",username);
    jsonObj.put("data",dataValue);

    // Create the POST object and add the parameters
    HttpPost httpPost = new HttpPost(url);
    StringEntity entity = new StringEntity(jsonObj.toString(),HTTP.UTF_8);
    entity.setContentType("application/json");
    httpPost.setEntity(entity);

    HttpClient client = new DefaultHttpClient();
    HttpResponse response = client.execute(httpPost);

希望这有助于解决您的问题.谢谢.

android – 使用HttpClient的HTTP请求太慢了?

android – 使用HttpClient的HTTP请求太慢了?

我正在尝试编写一个 Android应用程序,它将一些帖子值发送到托管在专用服务器上的PHP文件并存储数组resoult

代码是这样的

HttpPost httppost;
    DefaultHttpClient httpclient;

    httppost = new HttpPost("http://IP/script.PHP"); 
    HttpParams param = new BasicHttpParams(); 
    param.setParameter(CoreProtocolPNames.PROTOCOL_VERSION,HttpVersion.HTTP_1_1);


  //  httppost.getParams().setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE,false);

    HttpProtocolParams.setContentCharset(param,"UTF-8");

    httpclient = new DefaultHttpClient(param);

    ResponseHandler <String> res=new BasicResponseHandler(); 
    List<NameValuePair> nameValuePairs;

    nameValuePairs = new ArrayList<NameValuePair>(); 
    nameValuePairs.add(new BasicNameValuePair("id","1"));
    nameValuePairs.add(new BasicNameValuePair("api","1"));


    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 
Log.v("1",System.currentTimeMillis()+"");// Log to kNow the time diff
    String result= httpclient.execute(httppost,res);
Log.v("2",System.currentTimeMillis()+""); //  Log to kNow the time diff

这段代码浪费了大约2.5秒(在3G或WiFi上)发送帖子并从服务器获得“ok”字符串,即使有好的wifi这次只下来2.2 / 2.0秒

我在我的计算机上运行了一个简单的Ajax发送邮件脚本,通过同一部手机和3G连接到互联网,需要大约.300ms才能做同样的事情¿相同的连接,相同的动作,2秒的差异?

/// *** UPDATE

我在我的计算机上再次尝试了我的jquery脚本(带有移动3G / HDSPA连接)

平均时间响应约为250毫秒,但总是第一次请求高达1.7秒,我试图发送间隔为30秒的帖子,我得到平均1.5秒的时间,然后我试图发送间隔为2秒的帖子,第一次是1.41s,接近252ms

在这里,你们可以查看图表:http://i46.tinypic.com/27zjl8n.jpg

这种与电缆连接(标准家庭DSL)相同的测试始终提供约170ms间隔的固定时间响应(这里没有可靠的参数,但恕我直言,可能第一次尝试略高一点)

因此,在第一次尝试中有一些(或错误的)严重影响移动连接的东西,任何想法的人?

解决方法

尝试使用此配置

HttpClient httpclient = new DefaultHttpClient();
HttpParams httpParameters = httpclient.getParams();
httpconnectionParams.setConnectionTimeout(httpParameters,CONNECTION_TIMEOUT);
httpconnectionParams.setSoTimeout(httpParameters,WAIT_RESPONSE_TIMEOUT);
httpconnectionParams.setTcpNoDelay(httpParameters,true);

这是关于setTcpNoDelay的javadoc:

public static void setTcpNoDelay(HttpParams params,boolean value)

Since: API Level 1

Determines whether Nagle’s algorithm is to be used. The Nagle’s
algorithm tries to conserve bandwidth by minimizing the number of
segments that are sent. When applications wish to decrease network
latency and increase performance,they can disable Nagle’s algorithm
(that is enable TCP_NODELAY). Data will be sent earlier,at the cost
of an increase in bandwidth consumption.

Parameters

value true if the Nagle’s algorithm is to NOT be used (that is enable TCP_NODELAY),false otherwise.

Android 使用 httpClient 取消http请求的方法

Android 使用 httpClient 取消http请求的方法

其实apache还是提供了释放 连接资源的方法的,不过是埋得深了点。 

httpClient.getConnectionManager().shutdown();

这个shutdown并不是将手机网络断掉,而是将建立Http连接请求时所分配的资源释放掉。

C#爬虫基础之HttpClient获取HTTP请求与响应

C#爬虫基础之HttpClient获取HTTP请求与响应

一、概述

Net4.5以上的提供基本类,用于发送 HTTP 请求和接收来自通过 URI 确认的资源的 HTTP 响应。

HttpClient是一个高级 API,用于包装其运行的每个平台上可用的较低级别功能。

// HttpClient is intended to be instantiated once per application, rather than per-use. See Remarks.
static readonly HttpClient client = new HttpClient();
 
static async Task Main()
{
  // Call asynchronous network methods in a try/catch block to handle exceptions.
  try    
  {
     HttpResponseMessage response = await client.GetAsync("http://www.contoso.com/");
     response.EnsureSuccessStatusCode();
     string responseBody = await response.Content.ReadAsStringAsync();
     // Above three lines can be replaced with new helper method below
     // string responseBody = await client.GetStringAsync(uri);

     Console.WriteLine(responseBody);
  }  
  catch(HttpRequestException e)
  {
     Console.WriteLine("\nException Caught!");    
     Console.WriteLine("Message :{0} ",e.Message);
  }
}

二、HttpClient的使用

1.使用HttpClient调用Oauth的授权接口获取access_token

1)OAuth使用的密码式

2)获取到access_token后才进行下一步

2.带着access_token调用接口

1)hearder上添加bearer方式的access_token

2)调用接口确保成功获取到返回的结果

try
{
    string host = ConfigurationManager.AppSettings["api_host"];
    string username = ConfigurationManager.AppSettings["api_username"];
    string password = ConfigurationManager.AppSettings["api_password"];

    HttpClient httpClient = new HttpClient();

    // 设置请求头信息
    httpClient.DefaultRequestHeaders.Add("Host", host);
    httpClient.DefaultRequestHeaders.Add("Method", "Post");
    httpClient.DefaultRequestHeaders.Add("KeepAlive", "false");   // HTTP KeepAlive设为false,防止HTTP连接保持
    httpClient.DefaultRequestHeaders.Add("UserAgent","Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.95 Safari/537.11");

    //获取token
    var tokenResponse = httpClient.PostAsync("http://" + host + "/token", new FormUrlEncodedContent(new Dictionary<string, string> {
                {"grant_type","password"},
                {"username", username},
                {"password", password}
            }));
    tokenResponse.Wait();
    tokenResponse.Result.EnsureSuccessStatusCode();
    var tokenRes = tokenResponse.Result.Content.ReadAsStringAsync();
    tokenRes.Wait();
    var token = Newtonsoft.Json.Linq.JObject.Parse(tokenRes.Result);
    var access_token = token["access_token"].ToString();

    // 调用接口发起POST请求
    var authenticationHeaderValue = new AuthenticationHeaderValue("bearer", access_token);
    httpClient.DefaultRequestHeaders.Authorization = authenticationHeaderValue;
var content = new StringContent(parameter);
    content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
    var response = httpClient.PostAsync("http://" + host + "/" + api_address, content);

    response.Wait();
    response.Result.EnsureSuccessStatusCode();
    var res = response.Result.Content.ReadAsStringAsync();
    res.Wait();return Newtonsoft.Json.JsonConvert.DeserializeObject(res.Result);
}
catch (Exception ex)
{

    return ResultEx.Init(ex.Message);
}

HttpClient 获取图片并保存到本机

class Program
{
    static void Main()
    {
        //图片路径:https://img.infinitynewtab.com/wallpaper/1.jpg
        string imgSourceURL = "https://img.infinitynewtab.com/wallpaper/";
        DownloadImags(imgSourceURL).Wait();
    }
    private static async Task DownloadImags(string url)
    {
        var client = new HttpClient();
        System.IO.FileStream fs;
        int a = 1;
        //文件名:序号+.jpg。可指定范围,以下是获取100.jpg~500.jpg.
        for (int i = 100; i <= 500; i++)
        {
            var uri = new Uri(Uri.EscapeUriString(url+i.ToString()+".jpg"));
            byte[] urlContents = await client.GetByteArrayAsync(uri);
            fs = new System.IO.FileStream(AppDomain.CurrentDomain.BaseDirectory + "\\images\\"+ i.ToString() + ".jpg",System.IO.FileMode.CreateNew);
            fs.Write(urlContents, 0, urlContents.Length);
            Console.WriteLine(a++);
        }
    }
}

以下为封装的类库

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;


public class HttpClientHelpClass
{
    /// 
    /// get请求
    /// 
    /// 
    /// 
    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(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(s);
        }
        return result;
    }

    /// 
    /// post请求
    /// 
    /// 
    /// post数据
    /// 
    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;
    }

    /// 
    /// 发起post请求
    /// 
    /// 
    /// url
    /// post数据
    /// 
    public static T PostResponse(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(s);
        }
        return result;
    }


    /// 
    /// 反序列化Xml
    /// 
    /// 
    /// 
    /// 
    public static T XmlDeserialize(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;
    }

    /// 
    /// 修改API
    /// 
    /// 
    /// 
    /// 
    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;
    }

    /// 
    /// 创建API
    /// 
    /// 
    /// 
    /// 
    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;
    }

    /// 
    /// 删除API
    /// 
    /// 
    /// 
    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;
    }

    /// 
    /// 修改或者更改API        
    /// 
    /// 
    /// 
    /// 
    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;
    }

    /// 
    /// 检索API
    /// 
    /// 
    /// 
    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#使用HttpClient获取HTTP请求与响应的文章就介绍到这了。希望对大家的学习有所帮助,也希望大家多多支持。

您可能感兴趣的文章:
  • C#多线程TPL模式下使用HttpClient
  • C#中HttpClient使用注意(预热与长连接)
  • C#客户端HttpClient请求认证及数据传输
  • C#使用HttpClient的正确方式你了解吗
  • c# HttpClient设置超时的步骤
  • C# HttpClient Post参数同时上传文件的实现

我们今天的关于<经验>使用HttpClient做Http请求httpclient怎么用的分享已经告一段落,感谢您的关注,如果您想了解更多关于Android HttpClient,DefaultHttpClient,HttpPost、android – 使用HttpClient的HTTP请求太慢了?、Android 使用 httpClient 取消http请求的方法、C#爬虫基础之HttpClient获取HTTP请求与响应的相关信息,请在本站查询。

本文标签: