Http编程之HttpClient
C# 自带 HttpClient我这段代码为什么会报请求没完成就发另一个呢 我觉得完成了啊
C# 自带 HttpClient我这段代码为什么会报请求没完成就发
另一个呢我觉得完成了啊
C# 自带的 HttpClient 封装了访问 HTTP 服务的方法。
它可以使用GET 和 POST 等方法及时发送 HTTP 请求并获取 HTTP 响应的返回值。
但是在使用的过程中,有时候会发生一种情况,就是在一次请求还没
有完成时,就会发起另一次请求,从而导致报错。
主要原因是因为 C# 中的 Httpclient 并没有设置最大连接数的限制,因此可能会出现快速攻击的行为而失败。
另外,使用过程中,重复建
立 HttpClient 实例的情况也可能会出现失败的情况。
毕竟,如果不
断的建立新的 HttpClient 实例,则会造成内存占用问题,也可能导
致请求失败。
总而言之,要避免 HttpClient 报请求没完成就发另一个的情况,要
做的就是控制好 HttpClient 的连接数,避免连接数过多,把建立实
例的行为放在一个固定的循环外,避免在一个请求未完成前就去建立
新的实例。
C#中使用HttpClient来Post数据的内容HttpContent的各种格式
C#中使⽤HttpClient来Post数据的内容HttpContent的各种格式⼀、以下是最常⽤的四种类型:(1)、application/x-www-form-urlencoded这应该是最常见的 POST 提交数据的⽅式了。
浏览器的原⽣ <form> 表单,如果不设置 enctype 属性,那么最终就会以 application/x-www-form-urlencoded ⽅式提交数据。
<form action="form_action.asp" enctype="text/plain"><p>First name: <input type="text" name="fname" /></p><p>Last name: <input type="text" name="lname" /></p><input type="submit" value="Submit" /></form>(2)、multipart/form-data这也是常见的post请求⽅式,⼀般⽤来上传⽂件,各⼤服务器的⽀持也⽐较好。
所以我们使⽤表单上传⽂件时,必须让<form>表单的enctype属性值为 multipart/form-data.(3)、application/jsonapplication/json作为响应头并不陌⽣,实际上,现在很多时候也把它作为请求头,⽤来告诉服务端消息主体是序列化的JSON字符串,除了低版本的IE,基本都⽀持。
除了低版本的IE都⽀持JSON.stringify()的⽅法,服务端也有处理JSON的函数,使⽤json不会有任何⿇烦。
HTTPClient用法
HttpClient的用法HTTP 协议可能是现在 Internet 上使用得最多、最重要的协议了,越来越多的 Java 应用程序需要直接通过HTTP 协议来访问网络资源。
Commons-httpclient项目就是专门设计来简化HTTP客户端与服务器进行各种通讯编程。
通过它可以让原来很头疼的事情现在轻松的解决,例如你不再管是HTTP或者HTTPS的通讯方式,告诉它你想使用HTTPS方式,剩下的事情交给 httpclient替你完成。
首先,我们必须安装好 HttpClient。
HttpClient 可以在/commons/httpclient/downloads.html下载.HttpClient 用到了 Apache Jakarta common 下的子项目 logging,你可以从这个地址/site/downloads /downloads_commons-logging.cgi下载到 common logging,从下载后的压缩包中取出 commons-logging.jar 加到 CLASSPATH 中.HttpClient 用到了 Apache Jakarta common 下的子项目 codec,你可以从这个地址/site/downloads /downloads_commons-codec.cgi 下载到最新的 common codec,从下载后的压缩包中取出 commons-codec-1.x.jar 加到 CLASSPATH 中1.读取网页(HTTP/HTTPS)内容下面是我们给出的一个简单的例子用来访问某个页面package http.demo;import java.io.IOException;import mons.httpclient.*;import mons.httpclient.methods.*;/*** 最简单的HTTP客户端,用来演示通过GET或者POST方式访问某个页面* @author Liudong*/public class SimpleClient {public static void main(String[] args) throws IOException{HttpClient client = new HttpClient();//设置代理服务器地址和端口//client.getHostConfiguration().setProxy("proxy_host_addr",proxy_port);//使用GET方法,如果服务器需要通过HTTPS连接,那只需要将下面URL中的http换成https HttpMethod method = new GetMethod("");//使用POST方法//HttpMethod method = new PostMethod("");client.executeMethod(method);//打印服务器返回的状态System.out.println(method.getStatusLine());//打印返回的信息System.out.println(method.getResponseBodyAsString());//释放连接method.releaseConnection();}}在这个例子中首先创建一个HTTP客户端(HttpClient)的实例,然后选择提交的方法是GET或者 POST,最后在HttpClient实例上执行提交的方法,最后从所选择的提交方法中读取服务器反馈回来的结果。
javahttpput请求方式_使用HttpClient发送GETPOSTPUTDe
javahttpput请求方式_使用HttpClient发送GETPOSTPUTDe在Java中,我们可以使用HttpClient库来发送HTTP请求,包括GET、POST、PUT、DELETE等请求方式。
下面是使用HttpClient发送这些请求的示例代码。
1.发送GET请求:```javapublic class HttpGetExamplepublic static void main(String[] args) throws Exceptionint statusCode = response.getStatusLine(.getStatusCode(;System.out.println("Status Code: " + statusCode);//处理响应数据//...}```2.发送POST请求:```javapublic class HttpPostExamplepublic static void main(String[] args) throws Exception//设置请求体StringEntity requestBody = new StringEntity("request body", "UTF-8");int statusCode = response.getStatusLine(.getStatusCode(;System.out.println("Status Code: " + statusCode);//处理响应数据//...}```3.发送PUT请求:```javapublic class HttpPutExamplepublic static void main(String[] args) throws Exception//设置请求体StringEntity requestBody = new StringEntity("request body", "UTF-8");int statusCode = response.getStatusLine(.getStatusCode(;System.out.println("Status Code: " + statusCode);//处理响应数据//...}```4.发送DELETE请求:```javapublic class HttpDeleteExamplepublic static void main(String[] args) throws Exceptionint statusCode = response.getStatusLine(.getStatusCode(;System.out.println("Status Code: " + statusCode);//处理响应数据//...}```以上代码示例了如何使用HttpClient库发送GET、POST、PUT、DELETE请求,并处理响应数据。
浅谈HttpClient、okhttp和RestTemplate的区别
浅谈HttpClient、okhttp和RestTemplate的区别⼀、HttpClient1、pom依赖<!--HttpClient--><dependency><groupId>commons-httpclient</groupId><artifactId>commons-httpclient</artifactId><version>3.1</version></dependency>2、HttpClient代码实现public class HttpClientUtil {/*** httpClient的get请求⽅式* 使⽤GetMethod来访问⼀个URL对应的⽹页实现步骤:* 1.⽣成⼀个HttpClient对象并设置相应的参数;* 2.⽣成⼀个GetMethod对象并设置响应的参数;* 3.⽤HttpClient⽣成的对象来执⾏GetMethod⽣成的Get⽅法;* 4.处理响应状态码;* 5.若响应正常,处理HTTP响应内容;* 6.释放连接。
* @param url* @param charset* @return*/public static String doGet(String url, String charset) {//1.⽣成HttpClient对象并设置参数HttpClient httpClient = new HttpClient();//设置Http连接超时为5秒httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(5000);//2.⽣成GetMethod对象并设置参数GetMethod getMethod = new GetMethod(url);//设置get请求超时为5秒getMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 5000);//设置请求重试处理,⽤的是默认的重试处理:请求三次getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());String response = "";//3.执⾏HTTP GET 请求try {int statusCode = httpClient.executeMethod(getMethod);//4.判断访问的状态码if (statusCode != HttpStatus.SC_OK) {System.err.println("请求出错:" + getMethod.getStatusLine());}//5.处理HTTP响应内容//HTTP响应头部信息,这⾥简单打印Header[] headers = getMethod.getResponseHeaders();for(Header h : headers) {System.out.println(h.getName() + "---------------" + h.getValue());}//读取HTTP响应内容,这⾥简单打印⽹页内容//读取为字节数组byte[] responseBody = getMethod.getResponseBody();response = new String(responseBody, charset);System.out.println("-----------response:" + response);//读取为InputStream,在⽹页内容数据量⼤时候推荐使⽤//InputStream response = getMethod.getResponseBodyAsStream();} catch (HttpException e) {//发⽣致命的异常,可能是协议不对或者返回的内容有问题System.out.println("请检查输⼊的URL!");e.printStackTrace();} catch (IOException e) {//发⽣⽹络异常System.out.println("发⽣⽹络异常!");} finally {//6.释放连接getMethod.releaseConnection();}return response;}/*** post请求* @param url* @param json* @return*/public static String doPost(String url, JSONObject json){HttpClient httpClient = new HttpClient();PostMethod postMethod = new PostMethod(url);postMethod.addRequestHeader("accept", "*/*");postMethod.addRequestHeader("connection", "Keep-Alive");//设置json格式传送postMethod.addRequestHeader("Content-Type", "application/json;charset=GBK");//必须设置下⾯这个HeaderpostMethod.addRequestHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.81 Safari/537.36"); //添加请求参数postMethod.addParameter("commentId", json.getString("commentId"));String res = "";try {int code = httpClient.executeMethod(postMethod);if (code == 200){res = postMethod.getResponseBodyAsString();System.out.println(res);}} catch (IOException e) {e.printStackTrace();}return res;}public static void main(String[] args) {System.out.println(doGet("/cc/json/mobile_tel_segment.htm?tel=130********", "GBK"));System.out.println("-----------分割线------------");System.out.println("-----------分割线------------");System.out.println("-----------分割线------------");JSONObject jsonObject = new JSONObject();jsonObject.put("commentId", "130********");System.out.println(doPost("/cc/json/mobile_tel_segment.htm?tel=130********", jsonObject));}}3、建议代码复杂,还得操⼼资源回收等。
C#中HttpClient的简单使用
C#中HttpClient的简单使⽤介绍当我们在开发客户端还有少部分服务端程序时,数据需要从 Webapi 服务器取得。
在以前我使⽤的⽐较多的时和,在新的 .Net 版本中,团队为其带来了更多的可选择性——新的。
它有着更加灵活的 API。
发送请求和接收响应主要是通过 HttpRequestMessage 和HttpResponseMessage 这来给你个类,通过属性 Content 获取 http 响应内容。
区别HttpClient 与 WebClient 和 HttpWebRequest 相⽐,有以下⼏个主义的1. HttpClient 实例初始化时不与服务器域名或者主机地址绑定,也就是說可以通过⼀个 HttpClient 实例发送多个不同的请求(⽐如同⼀个HttpClient 请求和两个服务器数据)2. HttpClient 通过设置 DefaultHeaders 设置 HttpHeader 并且应⽤于该实例的所有请求3. HttpClient 使⽤可以很容易的处理异步请求(Async / Await)使⽤⽅法HttpClient 提供有与 Http Method 匹配的⽅法,⽐如 GET / POST / PUT ...等。
先实现模拟⼀个 GET 请求,代码如下// 传⼊参数 url 为请求地址async Task Get(string uri = "/search";){// 使⽤ using 语法建⽴⼀个明确周期的 HttpClient 实例using (HttpClient client = new HttpClient()){try{// 设置超时限制,有效防⽌浪费资源client.Timeout = TimeSpan.FromSeconds(30);//使⽤ GetAsync 进⾏异步 HTTPGET 请求HttpResponseMessage response = await client.GetAsync(uri);// 判断服务器响应代码是否为 2XXresponse.EnsureSuccessStatusCode();//使⽤ await 语法读取响应内容string responseBody = await response.Content.ReadAsStringAsync();Console.WriteLine(responseBody);}catch (HttpRequestException e){Console.WriteLine("Error Message :{0} ", e.Message);}}}除了直接使⽤与 Http Method 对应的⽅法外,还可以单独构建 HttpRequestMessage 实例进⾏请求async Task Get(string uri = "/search";){using (HttpClient client = new HttpClient()){HttpRequestMessage httpRequest = new HttpRequestMessage(HttpMethod.Get, uri);await client.SendAsync(httpRequest).ContinueWith(responseTask =>{Console.WriteLine("Response: {0}", responseTask.Result);});}}⾄于 Post 请求,对于初次接触 HttpClient 的⼈可能显得有些复杂,⽐较折腾,另⼀篇⽂章再讲解。
HttpClient(五)--模拟表单上传文件
HttpClient(五)--模拟表单上传⽂件1.maven依赖<dependency><groupId>org.apache.httpcomponents</groupId><artifactId>httpclient</artifactId><version>4.5.2</version></dependency><dependency><groupId>org.apache.httpcomponents</groupId><artifactId>httpmime</artifactId><version>4.5.2</version></dependency>2.代码实现import java.io.File;import java.io.IOException;import org.apache.http.HttpEntity;import org.apache.http.HttpResponse;import org.apache.http.client.ClientProtocolException;import org.apache.http.client.HttpClient;import org.apache.http.client.config.RequestConfig;import org.apache.http.client.methods.HttpPost;import org.apache.http.entity.mime.MultipartEntityBuilder;import org.apache.http.impl.client.HttpClients;import org.apache.http.util.EntityUtils;public class HttpClientUpload {public static void main(String[] args) {// 将 fileUrl 上传到 url中,上传成功后,返回下载地址String url = "http://127.0.0.1:8080/Joe/upload";String fileUrl = "C:/abc.txt";try {System.out.println(post(url, "file", new File(fileUrl)));} catch (Exception e) {e.printStackTrace();}}/*** post:(上传).** @author Joe Date:2017年9⽉11⽇下午5:37:46* @param serverUrl* @param fileParamName* @param file* @return* @throws ClientProtocolException* @throws IOException*/public static String post(String serverUrl, String fileParamName, File file)throws ClientProtocolException, IOException {HttpPost httpPost = new HttpPost(serverUrl);MultipartEntityBuilder builder = MultipartEntityBuilder.create();// 上传的⽂件builder.addBinaryBody(fileParamName, file);HttpEntity httpEntity = builder.build();httpPost.setEntity(httpEntity);// 请求获取数据的超时时间、设置从connect// Manager获取Connection超时时间(因为⽬前版本是可以共享连接池的)、设置连接超时时间RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(10000).setConnectionRequestTimeout(3000) .setConnectTimeout(10000).build();httpPost.setConfig(requestConfig);HttpClient httpClient = HttpClients.createDefault();HttpResponse response = httpClient.execute(httpPost);return EntityUtils.toString(response.getEntity());}}。
C 使用libcurl做HttpClient
C++使用libcurl做HttpClient当使用C++做HTTP客户端时,目前通用的做法就是使用libcurl。
其官方网站的地址是http://curl.haxx.se/,该网站主要提供了Curl和libcurl。
Curl是命令行工具,用于完成FTP, FTPS, HTTP, HTTPS, GOPHER, TELNET, DICT, FILE 以及LDAP的命令的请求及接收回馈。
libcurl提供给开发者,用于使用C++跨平台的开发各种网络协议的请求及响应。
里面的文档非常齐全,不过都是英文的。
本文提供最简单的demo使用libcurl开发HttpClient。
主要包括同步的HTTP GET、HTTP POST、HTTPS GET、HTTPS POST。
下载libcurl包,如果使用Linux平台,建议下载源文件编译;如果使用Windows平台,建议下载Win32 - MSVC,下载地址是:http://curl.haxx.se/download.html#ifndef __HTTP_CURL_H__ #define __HTTP_CURL_H__ #include class CHttpClient { public:CHttpClient(void); ~CHttpClient(void); public:/** * @brief HTTP POST请求* @param strUrl 输入参数,请求的Url地址,如: *@param strPost 输入参数,使用如下格式para1=val1?2=val2&… * @param strResponse 输出参数,返回的内容* @return 返回是否Post成功*/ int Post(const std::string & strUrl, const std::string & strPost, std::string & strResponse); /** *@brief HTTP GET请求* @param strUrl 输入参数,请求的Url地址,如: * @param strResponse 输出参数,返回的内容* @return 返回是否Post成功*/ int Get(const std::string & strUrl, std::string & strResponse); /** * @brief HTTPS POST请求,无证书版本* @param strUrl 输入参数,请求的Url地址,如:https:// * @param strPost 输入参数,使用如下格式para1=val1?2=val2&…* @param strResponse 输出参数,返回的内容*@param pCaPath 输入参数,为CA证书的路径.如果输入为NULL,则不验证服务器端证书的有效性. * @return 返回是否Post成功*/ int Posts(const std::string & strUrl, const std::string & strPost, std::string & strResponse, const char * pCaPath = NULL); /** * @brief HTTPS GET请求,无证书版本* @param strUrl 输入参数,请求的Url地址,如:https:// *@param strResponse 输出参数,返回的内容*@param pCaPath 输入参数,为CA证书的路径.如果输入为NULL,则不验证服务器端证书的有效性. * @return 返回是否Post成功*/ int Gets(const std::string & strUrl, std::string & strResponse, const char * pCaPath = NULL); public: void SetDebug(bool bDebug); private: bool m_bDebug; }; #endif [cpp] view plaincopy#include "httpclient.h" #include "curl/curl.h"#include CHttpClient::CHttpClient(void) :m_bDebug(false) { } CHttpClient::~CHttpClient(void) { } static int OnDebug(CURL *, curl_infotype itype, char * pData, size_t size, void *) { if(itype == CURLINFO_TEXT){ //printf("[TEXT]%s\n", pData); }else if(itype == CURLINFO_HEADER_IN){ printf("[HEADER_IN]%s\n", pData); } else if(itype == CURLINFO_HEADER_OUT){ printf("[HEADER_OUT]%s\n", pData); } else if(itype == CURLINFO_DATA_IN){ printf("[DATA_IN]%s\n", pData); }else if(itype == CURLINFO_DATA_OUT){ printf("[DATA_OUT]%s\n", pData); } return 0; } static size_t OnWriteData(void* buffer, size_tsize, size_t nmemb, void* lpVoid) { std::string* str = dynamic_caststd::string*>((std::string *)lpVoid);if( NULL == str || NULL == buffer ) { return -1; } char* pData = (char*)buffer;str->append(pData, size * nmemb); return nmemb; } int CHttpClient::Post(const std::string & strUrl, const std::string & strPost, std::string & strResponse){ CURLcode res; CURL* curl = curl_easy_init(); if(NULL == curl) { returnCURLE_FAILED_INIT; } if(m_bDebug){ curl_easy_setopt(curl, CURLOPT_VERBOSE, 1); curl_easy_setopt(curl,CURLOPT_DEBUGFUNCTION, OnDebug); }curl_easy_setopt(curl, CURLOPT_URL, strUrl.c_str());curl_easy_setopt(curl, CURLOPT_POST, 1);curl_easy_setopt(curl, CURLOPT_POSTFIELDS, strPost.c_str()); curl_easy_setopt(curl,CURLOPT_READFUNCTION, NULL);curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, OnWriteData); curl_easy_setopt(curl,CURLOPT_WRITEDATA, (void *)&strResponse);curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1);curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, 3); curl_easy_setopt(curl, CURLOPT_TIMEOUT, 3); res = curl_easy_perform(curl);curl_easy_cleanup(curl); return res; } int CHttpClient::Get(const std::string & strUrl, std::string & strResponse) { CURLcode res; CURL* curl = curl_easy_init(); if(NULL == curl){ return CURLE_FAILED_INIT; }if(m_bDebug) { curl_easy_setopt(curl, CURLOPT_VERBOSE, 1);curl_easy_setopt(curl, CURLOPT_DEBUGFUNCTION, OnDebug); } pre name="code" class="cpp">curl_easy_setopt(curl, CURLOPT_URL, strUrl.c_str());curl_easy_setopt(curl, CURLOPT_READFUNCTION, NULL); curl_easy_setopt(curl,CURLOPT_WRITEFUNCTION, OnWriteData);curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)&strResponse); /** * 当多个线程都使用超时处理的时候,同时主线程中有sleep或是wait等操作。
Httpclient表单,json,multipartform-data提交---总结常用的方法
Httpclient表单,json,multipartform-data提交---总结常⽤的⽅法最近在项⽬中,⼀直在使⽤HttpClient 中的⽅法,这⾥我进⾏⼀些⽅法的汇总,也是结合了⼀些⼤⽜写的代码,以备不时之需 官话:HttpClient 是Apache Jakarta Common 下的⼦项⽬,可以⽤来提供⾼效的、最新的、功能丰富的⽀持 HTTP 协议的客户端编程⼯具包,并且它⽀持 HTTP 协议最新的版本和建议 在我的博客我的常⽤⼯具了中有关于httpclient 的常⽤⽅法,在平常的开发中是⾜够⽤了----------在这⾥我细致的总结⼀下 1.我们在使⽤httpclient 第⼀步就是创建CloseableHttpClient 实例,这也是官⽅推荐⽅法:CloseableHttpClient httpclient = HttpClients.createDefault() 2.创建 httpget 与 httppost 的实例,我们进⾏⽹络连接的关键步骤://post 请求HttpPost httppost =new HttpPost(url);// get请求HttpGet httpget =new HttpGet(url); 3. addHeader(arg0, arg1) :见名知意,可以为我们请求加上请求头,cookie//加cookie 头httppost.addHeader("Cookie","JSESSIONID=fnwebidwn==");//User-Agenthttppost.addHeader("User-Agent","Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36"); ...... 4. httppost.setEntity(entity); 放⼊需要传递的参数,只出现在post ⽅法中,因为get直接在地址后⾯追加参数。
C#调用接口实例httpclient(postman)
C#调⽤接⼝实例httpclient(postman)调⽤主体Get请求var httpClient = new HttpClient();var getTokenUrl = new Uri("接⼝⽹络地址");var response = httpClient.GetAsync(getTokenUrl).Result;var data = response.Content.ReadAsStringAsync().Result;//接⼝调⽤成功获取的数据JObject jsonInfo = (JObject)JsonConvert.DeserializeObject(data);string code = Convert.ToString(jsonInfo["errcode"]);View CodePost请求此处例举的是传headers,如果不需要注释掉#region调⽤接⼝(postman)string Url = "http://?.?.?.?:9900/weather";//请求的url地址//string ContentTypeS = "application/x-www-form-urlencoded"; //格式类型(x-www-form-urlencoded格式传参)string ContentTypeS = "application/json"; //格式类型(json格式传参)//string PostData = "mode=" + "insert" + "&data=" + json; //传送的数据(x-www-form-urlencoded传参)sendCS sendcs = new sendCS();sendcs.mode = "insert";sendcs.data = "12345";string jkid = "12345";//转jsonstring PostData = JsonConvert.SerializeObject(sendcs); //传送的数据(json传参)RestApiClient DXApiManager = new RestApiClient(Url, HttpVerbNew.POST, ContentTypeS, PostData, jkid);string returnInfo = DXApiManager.MakeRequest();//转为json对象(添加Newtonsoft.Json.dll引⽤)JObject jsonInfo = (JObject)JsonConvert.DeserializeObject(returnInfo);string code = Convert.ToString(jsonInfo["code"]);//输出结果string msg = Convert.ToString(jsonInfo["msg"]);//输出结果//再根据code返回值去判断成功或失败,返回结果#endregionView Code相关类public class RestApiClient{public string EndPoint { get; set; } //请求的url地址public HttpVerbNew Method { get; set; } //请求的⽅法public string ContentType { get; set; } //格式类型public string PostData { get; set; } //传送的数据public string JKID { get; set; } //headers 参数public RestApiClient(){EndPoint = "";Method = HttpVerbNew.GET;ContentType = "text/xml";PostData = "";}public RestApiClient(string endpoint, string contentType){EndPoint = endpoint;Method = HttpVerbNew.GET;ContentType = contentType;PostData = "";}public RestApiClient(string endpoint, HttpVerbNew method, string contentType){EndPoint = endpoint;Method = method;ContentType = contentType;PostData = "";}public RestApiClient(string endpoint, HttpVerbNew method, string contentType, string postData,string jkid){EndPoint = endpoint;Method = method;ContentType = contentType;PostData = postData;JKID = jkid;}// 添加httpsprivate static readonly string DefaultUserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)";private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors){if (errors == SslPolicyErrors.None)return true;return false;}// end添加httpspublic string MakeRequest(){return MakeRequest("");}public string MakeRequest(string parameters){// 添加httpsif (EndPoint.Substring(0, 8) == "https://"){ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;}var request = (HttpWebRequest)HttpWebRequest.Create(EndPoint + parameters);if (EndPoint.Substring(0, 8) == "https://"){//string clientp12path = AppDomain.CurrentDomain.BaseDirectory + "\\Certificate\\outgoing.CertwithKey.pkcs12";//string clientp12PassWord = "IoM@1234";//string clientp12path2 = AppDomain.CurrentDomain.BaseDirectory + "\\Certificate\\server.pem";//string clientp12PassWord2 = "1qaz2wsx";//X509Store certStore = new X509Store(StoreName.My, StoreLocation.LocalMachine);//certStore.Open(OpenFlags.ReadOnly);//X509Certificate2 cer = new X509Certificate2(clientp12path, clientp12PassWord);//X509Certificate2 cer2 = new X509Certificate2(clientp12path2, clientp12PassWord2);//request.ClientCertificates.Add(cer);//request.ClientCertificates.Add(cer2);ServicePointManager.ServerCertificateValidationCallback += (object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) => {return true;};erAgent = DefaultUserAgent;}// end添加httpsrequest.Method = Method.ToString();request.ContentLength = 0;request.ContentType = ContentType;request.ProtocolVersion = HttpVersion.Version10;request.Headers.Add("alpha_auth_token", "asdf12345");request.Headers.Add("alpha_auth_jkid", JKID);if (!string.IsNullOrEmpty(PostData) && Method == HttpVerbNew.POST)//如果传送的数据不为空,并且⽅法是post{var encoding = new UTF8Encoding();var bytes = Encoding.UTF8.GetBytes(PostData);//编码⽅式按⾃⼰需求进⾏更改,我在项⽬中使⽤的是UTF-8request.ContentLength = bytes.Length;using (var writeStream = request.GetRequestStream()){writeStream.Write(bytes, 0, bytes.Length);}}else if (!string.IsNullOrEmpty(PostData) && Method == HttpVerbNew.PUT)//如果传送的数据不为空,并且⽅法是put{var encoding = new UTF8Encoding();var bytes = Encoding.UTF8.GetBytes(PostData);//编码⽅式按⾃⼰需求进⾏更改,我在项⽬中使⽤的是UTF-8request.ContentLength = bytes.Length;using (var writeStream = request.GetRequestStream()){writeStream.Write(bytes, 0, bytes.Length);}}using (var response = (HttpWebResponse)request.GetResponse()){var responseValue = string.Empty;if (response.StatusCode != HttpStatusCode.OK && response.StatusCode != HttpStatusCode.NoContent && response.StatusCode != HttpStatusCode.Created) {var message = response.StatusCode.ToString();throw new ApplicationException(message);}// grab the responseusing (var responseStream = response.GetResponseStream()){if (responseStream != null)using (var reader = new StreamReader(responseStream)){responseValue = reader.ReadToEnd();}}return responseValue;}}}public enum HttpVerbNew{GET, //method 常⽤的就这⼏样,可以添加其他的 get:获取 post:修改 put:写⼊ delete:删除POST,PUT,DELETE}View Codehttpclient万能写法现在postman越来越便利,当我们⽤postman调通接⼝后,可直接⼀键成⽣code(postman版本不同位置不同)举例:点击后可⼀键⽣成代码扔进项⽬⾥就可运⾏前提需要添加⼀个NuGet包 --- RestSharp (版本:106.12.0.0 107版本⽅法构造改变了暂时不知道怎么⽤)。
Feign使用HttpClient和OkHttp方式
Feign使用HttpClient和OkHttp方式1. Feign使用HttpClient方式:Feign默认使用的是JDK自带的HttpURLConnection作为HTTP客户端,但也可以使用HttpClient进行替换。
使用HttpClient方式需要添加对应的依赖,例如Apache HttpClient。
a.添加依赖:```xml<dependency><version>4.5.13</version></dependency>```b. 配置FeignClient:```javapublic class FeignClientConfigreturn HttpClientBuilder.create(.build(;}public Feign.Builder feignBuilde}}c. 使用FeignClient:```javapublic interface ExampleClientString getExample(;}```2. Feign使用OkHttp方式:OkHttp是一个高效的HTTP客户端库,Feign也可以使用OkHttp替代默认的HTTP客户端。
a.添加依赖:```xml<dependency><version>4.9.1</version></dependency><dependency><groupId>io.github.openfeign</groupId><version>11.6</version></dependency>b. 配置FeignClient:```javapublic class FeignClientConfigpublic OkHttpClient okHttpClienreturn new OkHttpClient(;}public Feign.Builder feignBuildereturn Feign.builder(.client(new OkHttpClient();}}```c. 使用FeignClient:```javapublic interface ExampleClientString getExample(;}```总结:Feign支持使用HttpClient和OkHttp作为HTTP客户端,可以根据实际需求选择适合的方式。
HttpClient详细使用示例详解
HttpClient详细使⽤⽰例详解⽬录进⼊正题详细使⽤⽰例HttpClient 是Apache Jakarta Common 下的⼦项⽬,可以⽤来提供⾼效的、最新的、功能丰富的⽀持 HTTP 协议的客户端编程⼯具包,并且它⽀持 HTTP 协议最新的版本和建议。
HTTP 协议可能是现在 Internet 上使⽤得最多、最重要的协议了,越来越多的 Java 应⽤程序需要直接通过 HTTP 协议来访问⽹络资源。
虽然在 JDK 的 java net包中已经提供了访问 HTTP 协议的基本功能,但是对于⼤部分应⽤程序来说,JDK 库本⾝提供的功能还不够丰富和灵活。
HttpClient 是 Apache Jakarta Common 下的⼦项⽬,⽤来提供⾼效的、最新的、功能丰富的⽀持 HTTP 协议的客户端编程⼯具包,并且它⽀持 HTTP 协议最新的版本和建议。
HTTP和浏览器有点像,但却不是浏览器。
很多⼈觉得既然HttpClient是⼀个HTTP客户端编程⼯具,很多⼈把他当做浏览器来理解,但是其实HttpClient不是浏览器,它是⼀个HTTP通信库,因此它只提供⼀个通⽤浏览器应⽤程序所期望的功能⼦集,最根本的区别是HttpClient中没有⽤户界⾯,浏览器需要⼀个渲染引擎来显⽰页⾯,并解释⽤户输⼊,例如⿏标点击显⽰页⾯上的某处,有⼀个布局引擎,计算如何显⽰HTML页⾯,包括级联样式表和图像。
javascript解释器运⾏嵌⼊HTML页⾯或从HTML页⾯引⽤的javascript代码。
来⾃⽤户界⾯的事件被传递到javascript解释器进⾏处理。
除此之外,还有⽤于插件的接⼝,可以处理Applet,嵌⼊式媒体对象(如pdf⽂件,Quicktime电影和Flash动画)或ActiveX控件(可以执⾏任何操作)。
HttpClient只能以编程的⽅式通过其API⽤于传输和接受HTTP消息。
HttpClient的主要功能:实现了所有 HTTP 的⽅法(GET、POST、PUT、HEAD、DELETE、HEAD、OPTIONS 等)⽀持 HTTPS 协议⽀持代理服务器(Nginx等)等⽀持⾃动(跳转)转向……进⼊正题环境说明:JDK1.8、SpringBoot准备环节第⼀步:在pom.xml中引⼊HttpClient的依赖第⼆步:引⼊fastjson依赖注:本⼈引⼊此依赖的⽬的是,在后续⽰例中,会⽤到“将对象转化为json字符串的功能”,也可以引其他有此功能的依赖。
C++实现轻量级极简httpserver和httpclient(转)
C++实现轻量级极简httpserver和httpclient(转)⼀般来说,C++的项⽬多是偏底层,不怎么需要跟http打交道,但有时候⼜需要在C++后端项⽬中加⼊⼀些简单 http接⼝,⽐如游戏运营服务器,⾦融交易监控服务等。
但是传统的实现⽅法⽐如采⽤libcurl,asio等较为重型的框架来做有没有必要,因此,这⾥采⽤这个库来实现基本的httpserver和httpclient功能,⾮常简单,包含⼀个h⽂件,⼀个cpp⽂件到⼯程中就⾏了,⽆需编译,⽆需链接库。
本⽂实现了⼀个project,将mongoose中提供的http相关api封装成了httpserver类和httpclient类,⽅便调⽤,⽬录结构如下:├─common├─mongoose.h└─mongoose.cpp├─httpclient├─http_client.h├─http_client.cpp└─main.cpp└─httpserver└─web└─index.html├─http_server.h├─http_server.cpp└─main.cpp编译环境:win10,vs2015, C++11 (其实是跨平台的)http_server.h#pragma once#include <string>#include <unordered_map>#include <functional>#include "../common/mongoose.h"// 定义http返回callbacktypedef void OnRspCallback(mg_connection *c, std::string);// 定义http请求handlerusing ReqHandler = std::function<bool (std::string, std::string, mg_connection *c, OnRspCallback)>;class HttpServer{public:HttpServer() {}~HttpServer() {}void Init(const std::string &port); // 初始化设置bool Start(); // 启动httpserverbool Close(); // 关闭void AddHandler(const std::string &url, ReqHandler req_handler); // 注册事件处理函数void RemoveHandler(const std::string &url); // 移除时间处理函数static std::string s_web_dir; // ⽹页根⽬录static mg_serve_http_opts s_server_option; // web服务器选项static std::unordered_map<std::string, ReqHandler> s_handler_map; // 回调函数映射表private:// 静态事件响应函数static void OnHttpEvent(mg_connection *connection, int event_type, void *event_data);static void HandleEvent(mg_connection *connection, http_message *http_req);static void SendRsp(mg_connection *connection, std::string rsp);std::string m_port; // 端⼝mg_mgr m_mgr; // 连接管理器};http_server.cpp#include <utility>#include "http_server.h"void HttpServer::Init(const std::string &port){m_port = port;s_server_option.enable_directory_listing = "yes";s_server_option.document_root = s_web_dir.c_str();// TODO:其他设置}bool HttpServer::Start(){mg_mgr_init(&m_mgr, NULL);mg_connection *connection = mg_bind(&m_mgr, m_port.c_str(), OnHttpEvent);if (connection == NULL)return false;mg_set_protocol_http_websocket(connection);printf("starting http server at port: %s\n", m_port.c_str());// loopwhile (true)mg_mgr_poll(&m_mgr, 500); // msreturn true;}void HttpServer::OnHttpEvent(mg_connection *connection, int event_type, void *event_data) {http_message *http_req = (http_message *)event_data;switch (event_type){case MG_EV_HTTP_REQUEST:HandleEvent(connection, http_req);break;default:break;}}static bool route_check(http_message *http_msg, char *route_prefix){if (mg_vcmp(&http_msg->uri, route_prefix) == 0)return true;elsereturn false;// TODO: 还可以判断 GET, POST, PUT, DELTE等⽅法//mg_vcmp(&http_msg->method, "GET");//mg_vcmp(&http_msg->method, "POST");//mg_vcmp(&http_msg->method, "PUT");//mg_vcmp(&http_msg->method, "DELETE");}void HttpServer::AddHandler(const std::string &url, ReqHandler req_handler){if (s_handler_map.find(url) != s_handler_map.end())return;s_handler_map.insert(std::make_pair(url, req_handler));}void HttpServer::RemoveHandler(const std::string &url){auto it = s_handler_map.find(url);if (it != s_handler_map.end())s_handler_map.erase(it);}void HttpServer::SendRsp(mg_connection *connection, std::string rsp){// 必须先发送headermg_printf(connection, "%s", "HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n"); // 以json形式返回mg_printf_http_chunk(connection, "{ \"result\": %s }", rsp.c_str());// 发送空⽩字符快,结束当前响应mg_send_http_chunk(connection, "", 0);}void HttpServer::HandleEvent(mg_connection *connection, http_message *http_req){std::string req_str = std::string(http_req->message.p, http_req->message.len);printf("got request: %s\n", req_str.c_str());// 先过滤是否已注册的函数回调std::string url = std::string(http_req->uri.p, http_req->uri.len);std::string body = std::string(http_req->body.p, http_req->body.len);auto it = s_handler_map.find(url);if (it != s_handler_map.end()){ReqHandler handle_func = it->second;handle_func(url, body, connection, SendRsp);}// 其他请求if (route_check(http_req, "/")) // index pagemg_serve_http(connection, http_req, s_server_option); else if (route_check(http_req, "/api/hello")){// 直接回传SendRsp(connection, "welcome to httpserver");}else if (route_check(http_req, "/api/sum")){// 简单post请求,加法运算测试char n1[100], n2[100];double result;/* Get form variables */mg_get_http_var(&http_req->body, "n1", n1, sizeof(n1));mg_get_http_var(&http_req->body, "n2", n2, sizeof(n2));/* Compute the result and send it back as a JSON object */ result = strtod(n1, NULL) + strtod(n2, NULL);SendRsp(connection, std::to_string(result));}else{mg_printf(connection,"%s","HTTP/1.1 501 Not Implemented\r\n""Content-Length: 0\r\n\r\n");}}bool HttpServer::Close(){mg_mgr_free(&m_mgr);return true;}index.html<!DOCTYPE html><html><head><title>RESTful API demo</title><script src="///jquery-1.11.0.min.js"></script> <script type="text/javascript">$(document).ready(function(){$("button").click(function(){$.get("/api/hello",function(data, status){console.log("get rsp: ", data);$('#result1').html(data);});});});$(document).on('keyup', '#n1, #n2', function() {$.ajax({url: '/api/sum',method: 'POST',dataType: 'json',data: { n1: $('#n1').val(), n2: $('#n2').val() },success: function(json) {console.log("post rsp: ", json);$('#result2').html(json.result);}});});</script></head><body><h1>c++ httpserver demo</h1><p>front end request</p><h2>GET</h2><div><button id="btn">get request</button></div><div><label>Result1:</label><span id="result1"></span></div><h2>POST</h2><div><label>Number 1:</label><input type="text" id="n1"/></div><div><label>Number 2:</label><input type="text" id="n2"/></div><div><label>Result2:</label><span id="result2"></span></div></body></html>main.cpp#include <iostream>#include <memory>#include "http_server.h"// 初始化HttpServer静态类成员mg_serve_http_opts HttpServer::s_server_option;std::string HttpServer::s_web_dir = "./web";std::unordered_map<std::string, ReqHandler> HttpServer::s_handler_map;bool handle_fun1(std::string url, std::string body, mg_connection *c, OnRspCallback rsp_callback) {// do sthstd::cout << "handle fun1" << std::endl;std::cout << "url: " << url << std::endl;std::cout << "body: " << body << std::endl;rsp_callback(c, "rsp1");return true;}bool handle_fun2(std::string url, std::string body, mg_connection *c, OnRspCallback rsp_callback) {// do sthstd::cout << "handle fun2" << std::endl;std::cout << "url: " << url << std::endl;std::cout << "body: " << body << std::endl;rsp_callback(c, "rsp2");return true;}int main(int argc, char *argv[]){std::string port = "7999";auto http_server = std::shared_ptr<HttpServer>(new HttpServer);http_server->Init(port);// add handlerhttp_server->AddHandler("/api/fun1", handle_fun1);http_server->AddHandler("/api/fun2", handle_fun2);http_server->RemoveHandler("/api/fun3");// http_server->RemoveHandler("/api/fun3");http_server->Start();return0;}服务器⽀持host静态页⾯资源,也⽀持rest api调⽤需要⼿动设置loop polling的时间间隔可以⾃定义静态页⾯根路径,注册和解注册⾃定义api函数回调某些变量必须声明定义成全局或者静态变量http客户端http_client.h#pragma once#include <string>#include <functional>#include "../common/mongoose.h"// 此处必须⽤function类,typedef再后⾯函数指针赋值⽆效using ReqCallback = std::function<void (std::string)>;class HttpClient{public:HttpClient() {}~HttpClient() {}static void SendReq(const std::string &url, ReqCallback req_callback);static void OnHttpEvent(mg_connection *connection, int event_type, void *event_data); static int s_exit_flag;static ReqCallback s_req_callback;};http_client.cpp#include "http_client.h"// 初始化client静态变量int HttpClient::s_exit_flag = 0;ReqCallback HttpClient::s_req_callback;// 客户端的⽹络请求响应void HttpClient::OnHttpEvent(mg_connection *connection, int event_type, void *event_data) {http_message *hm = (struct http_message *)event_data;int connect_status;switch (event_type){case MG_EV_CONNECT:connect_status = *(int *)event_data;if (connect_status != 0){printf("Error connecting to server, error code: %d\n", connect_status);s_exit_flag = 1;}break;case MG_EV_HTTP_REPLY:{printf("Got reply:\n%.*s\n", (int)hm->body.len, hm->body.p);std::string rsp = std::string(hm->body.p, hm->body.len);connection->flags |= MG_F_SEND_AND_CLOSE;s_exit_flag = 1; // 每次收到请求后关闭本次连接,重置标记// 回调处理s_req_callback(rsp);}break;case MG_EV_CLOSE:if (s_exit_flag == 0){printf("Server closed connection\n");s_exit_flag = 1;};break;default:break;}}// 发送⼀次请求,并回调处理,然后关闭本次连接void HttpClient::SendReq(const std::string &url, ReqCallback req_callback){// 给回调函数赋值s_req_callback = req_callback;mg_mgr mgr;mg_mgr_init(&mgr, NULL);auto connection = mg_connect_http(&mgr, OnHttpEvent, url.c_str(), NULL, NULL);mg_set_protocol_http_websocket(connection);printf("Send http request %s\n", url.c_str());// loopwhile (s_exit_flag == 0)mg_mgr_poll(&mgr, 500);mg_mgr_free(&mgr);}client每次请求都是⼀个独⽴的请求请求函数中加⼊回调⽤于处理⽹络返回测试可以⽤浏览器、或者其他⼯具提交url,查看⽹络请求返回GET请求结果{ "result": welcome to httpserver }POST请求结果{ "result": 38 }源码csdn:github:。
C#中HttpWebRequest、WebClient、HttpClient的使用详解
C#中HttpWebRequest、WebClient、HttpClient的使⽤详解HttpWebRequest:命名空间: ,这是.NET创建者最初开发⽤于使⽤HTTP请求的标准类。
使⽤HttpWebRequest可以让开发者控制请求/响应流程的各个⽅⾯,如 timeouts, cookies, headers, protocols。
另⼀个好处是HttpWebRequest类不会阻塞UI线程。
例如,当您从响应很慢的API服务器下载⼤⽂件时,您的应⽤程序的UI不会停⽌响应。
HttpWebRequest通常和WebResponse⼀起使⽤,⼀个发送请求,⼀个获取数据。
HttpWebRquest更为底层⼀些,能够对整个访问过程有个直观的认识,但同时也更加复杂⼀些。
123 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 //POST⽅法public static string HttpPost(string Url, string postDataStr){HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);request.Method = "POST";request.ContentType = "application/x-www-form-urlencoded";Encoding encoding = Encoding.UTF8;byte[] postData = encoding.GetBytes(postDataStr);request.ContentLength = postData.Length;Stream myRequestStream = request.GetRequestStream();myRequestStream.Write(postData, 0, postData.Length);myRequestStream.Close();HttpWebResponse response = (HttpWebResponse)request.GetResponse();Stream myResponseStream = response.GetResponseStream();StreamReader myStreamReader = new StreamReader(myResponseStream, encoding);string retString = myStreamReader.ReadToEnd();myStreamReader.Close();myResponseStream.Close();return retString;}//GET⽅法public static string HttpGet(string Url, string postDataStr){HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url + (postDataStr == ""? "": "?") + postDataStr); request.Method = "GET";request.ContentType = "text/html;charset=UTF-8";HttpWebResponse response = (HttpWebResponse)request.GetResponse();Stream myResponseStream = response.GetResponseStream();StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));string retString = myStreamReader.ReadToEnd();myStreamReader.Close();myResponseStream.Close();return retString;}WebClient:命名空间,WebClient是⼀种更⾼级别的抽象,是HttpWebRequest为了简化最常见任务⽽创建的,使⽤过程中你会发现他缺少基本的header,timeoust的设置,不过这些可以通过继承httpwebrequest来实现。
HttpClient 4.3教程(转载)
HttpClient提供URIBuilder工具类来简化URIs的创建和修改过程。
1. URI uri = new URIBuilder()2. .setScheme("http")3. .setHost("")4. .setPath("/search")5. .setParameter("q", "httpclient")6. .setParameter("btnG", "Google Search")7. .setParameter("aq", "f")8. .setParameter("oq", "")9. .build();10. HttpGet httpget = new HttpGet(uri);11. System.out.println(httpget.getURI());上述代码会在控制台输出:1. /search?q=httpclient&btnG=Google+Search&aq=f&oq=1.1.2. HTTP响应服务器收到客户端的http请求后,就会对其进行解析,然后把响应发给客户端,这个响应就是HTTP response.HTTP响应第一行是协议版本,之后是数字状态码和相关联的文本段。
1. HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1,2. HttpStatus.SC_OK, "OK");3.4. System.out.println(response.getProtocolVersion());5. System.out.println(response.getStatusLine().getStatusCode());6. System.out.println(response.getStatusLine().getReasonPhrase());7. System.out.println(response.getStatusLine().toString());上述代码会在控制台输出:1. HTTP/1.12. 2003. OK4. HTTP/1.1 200 OK1.1.3. 消息头一个Http消息可以包含一系列的消息头,用来对http消息进行描述,比如消息长度,消息类型等等。
【推荐下载】HttpClient源码解析系列:第四篇:Connection是怎么生成和管理的
HttpClient 源码解析系列:第四篇:Connection 是怎么生成和管理的2017/08/08 0 上面介绍了HttpClientConnection 是最核心的接口这个接口的使用分布在上图所示的类或者接口中。
图中可以看出,分成四个大类:Connection 的不同实现,Manager,Operator,Factory。
由于这里不着重考察Connection 的实现,因此略过,而考察Manager,Operator,Factory。
经过简单的代码筛查,可以发现在管理HttpClientConnection 过程中,它以一个子接口:ManagedHttpClientConnection的形式存在。
这个很容易理解,HttpClientConnection 的实例并不是用户new 出来的,而是经由Manager 管理的,因此衍生出一个Managed 的接口。
此外,Operator和Factory 也是经由Manager 来调用的,因此可以先从HttpClientConnectionManager来切入代码。
接口HttpClientConnectionManager 有两个实现显然,BasicHttpClientConnectionManager 是最基本的可用版本。
那么我们来看一下其中的代码。
从其中的参数可以看到,这里面有一个Connection 和一个Route,也就是说这个基础版的Manager 只能管理一个Connection。
来看最核心的方法:getConnection, connectsynchronized HttpClientConnection getConnection(final HttpRoute route, final Object state) {Asserts.check(!this.isShutdown.get(), Connection manager hasbeen shut down if (this.log.isDebugEnabled()) {this.log.debug( Get connection for route route);}Asserts.check(!this.leased, Connection is still allocated if (!LangUtils.equals(this.route, route) || !LangUtils.equals(this.state, state)) {closeConnection();}this.route = route; //创建链接的时候目标主机的信息是一定要的this.state = state;checkExpiry(); //校验是否存在if (this.conn == null) {this.conn = this.connFactory.create(route, this.connConfig); // 这个Manager 管理唯一一个Connection,如果获取连接的时候不存在则新建一个。
C#客户端HttpClient请求认证及数据传输
C#客户端HttpClient请求认证及数据传输⽬录⼀,授权认证1. 基础认证⽰例2. JWT 认证⽰例3. Cookie ⽰例⼆,请求类型三,数据传输1. Query2. Header3. 表单4. JSON5. 上传⽂件⼀,授权认证客户端请求服务器时,需要通过授权认证许可,⽅能获取服务器资源,⽬前⽐较常见的认证⽅式有 Basic 、JWT、Cookie。
HttpClient 是 C# 中的 HTTP/HTTPS 客户端,⽤于发送 HTTP 请求和接收来⾃通过 URI 确认的资源的 HTTP 响应。
下⾯以具体代码做⽰范。
1. 基础认证⽰例// Basic基础认证public async Task Basic(string user, string password, string url){// 如果认证页⾯是 https 的,请参考⼀下 jwt 认证的 HttpClientHandler// 创建 clientHttpClient client = new HttpClient();// 创建⾝份认证// using .Http.Headers;AuthenticationHeaderValue authentication = new AuthenticationHeaderValue("Basic",Convert.ToBase64String(Encoding.UTF8.GetBytes($"{user}:{password}")));client.DefaultRequestHeaders.Authorization = authentication;byte[] response = await client.GetByteArrayAsync(url);client.Dispose();}可以看到 Basic 认证的安全程度⾮常低,多⽤于路由器和嵌⼊式设备,⽽且往往不会使⽤ HTTPS。
httpclient使用详解
httpclient使用详解Http协议的重要性相信不用我多说了,HttpClient相比传统JDK自带的URLConnection,增加了易用性和灵活性(具体区别,日后我们再讨论),它不仅是客户端发送Http请求变得容易,而且也方便了开发人员测试接口(基于Http协议的),即提高了开发的效率,也方便提高代码的健壮性。
因此熟练掌握HttpClient是很重要的必修内容,掌握HttpClient后,相信对于Http协议的了解会更加深入。
一、简介HttpClient是Apache Jakarta Common下的子项目,用来提供高效的、最新的、功能丰富的支持HTTP协议的客户端编程工具包,并且它支持HTTP协议最新的版本和建议。
HttpClient已经应用在很多的项目中,比如Apache Jakarta上很著名的另外两个开源项目Cactus和HTMLUnit都使用了HttpClient。
下载地址: /downloads.cgi二、特性1. 基于标准、纯净的Java语言。
实现了Http1.0和Http1.12. 以可扩展的面向对象的结构实现了Http全部的方法(GET, POST, PUT, DELETE, HEAD, OPTIONS, and TRACE)。
3. 支持HTTPS协议。
4. 通过Http代理建立透明的连接。
5. 利用CONNECT方法通过Http代理建立隧道的https连接。
6. Basic, Digest, NTLMv1, NTLMv2, NTLM2 Session, SNPNEGO/Kerberos认证方案。
7. 插件式的自定义认证方案。
8. 便携可靠的套接字工厂使它更容易的使用第三方解决方案。
9. 连接管理器支持多线程应用。
支持设置最大连接数,同时支持设置每个主机的最大连接数,发现并关闭过期的连接。
10. 自动处理Set-Cookie中的Cookie。
11. 插件式的自定义Cookie策略。
Java调用HttpHttps接口(4)--HttpClient调用HttpHttps接口
Java调⽤HttpHttps接⼝(4)--HttpClient调⽤HttpHttps接⼝HttpClient是Apache HttpComponents项⽬下的⼀个组件,是Commons-HttpClient的升级版,两者api调⽤写法也很类似。
⽂中所使⽤到的软件版本:Java 1.8.0_191、HttpClient 4.5.10。
1、服务端参见2、调⽤Http接⼝2.1、GET请求public static void get() {String requestPath = "http://localhost:8080/demo/httptest/getUser?userId=1000&userName=李⽩";CloseableHttpClient httpClient = HttpClients.createDefault();try {HttpGet get = new HttpGet(requestPath);CloseableHttpResponse response = httpClient.execute(get);System.out.println("GET返回状态:" + response.getStatusLine());HttpEntity responseEntity = response.getEntity();System.out.println("GET返回结果:" + EntityUtils.toString(responseEntity));//流畅api调⽤String result = Request.Get(requestPath).execute().returnContent().asString(Charset.forName("utf-8"));System.out.println("GET fluent返回结果:" + result);} catch (Exception e) {e.printStackTrace();} finally {close(httpClient);}}2.2、POST请求(发送键值对数据)public static void post() {String requestPath = "http://localhost:8080/demo/httptest/getUser";CloseableHttpClient httpClient = HttpClients.createDefault();try {HttpPost post = new HttpPost(requestPath);List<NameValuePair> list = new ArrayList<NameValuePair>();list.add(new BasicNameValuePair("userId", "1000"));list.add(new BasicNameValuePair("userName", "李⽩"));post.setEntity(new UrlEncodedFormEntity(list, "utf-8"));CloseableHttpResponse response = httpClient.execute(post);System.out.println("POST返回状态:" + response.getStatusLine());HttpEntity responseEntity = response.getEntity();System.out.println("POST返回结果:" + EntityUtils.toString(responseEntity));//流畅api调⽤String result = Request.Post(requestPath).bodyForm(Form.form().add("userId", "1000").add("userName", "李⽩").build(), Charset.forName("utf-8")).execute().returnContent().asString(Charset.forName("utf-8"));System.out.println("POST fluent返回结果:" + result);} catch (Exception e) {e.printStackTrace();} finally {close(httpClient);}}2.3、POST请求(发送JSON数据)public static void post2() {String requestPath = "http://localhost:8080/demo/httptest/addUser";CloseableHttpClient httpClient = HttpClients.createDefault();try {HttpPost post = new HttpPost(requestPath);post.setHeader("Content-type", "application/json");String param = "{\"userId\": \"1001\",\"userName\":\"杜甫\"}";post.setEntity(new StringEntity(param, "utf-8"));CloseableHttpResponse response = httpClient.execute(post);System.out.println("POST json返回状态:" + response.getStatusLine());HttpEntity responseEntity = response.getEntity();System.out.println("POST josn返回结果:" + EntityUtils.toString(responseEntity));//流畅api调⽤String result = Request.Post(requestPath).addHeader("Content-type", "application/json").bodyString(param, ContentType.APPLICATION_JSON).execute().returnContent().asString(Charset.forName("utf-8"));System.out.println("POST json fluent返回结果:" + result);} catch (Exception e) {e.printStackTrace();} finally {close(httpClient);}}2.4、上传⽂件public static void upload() {String requestPath = "http://localhost:8080/demo/httptest/upload";CloseableHttpClient httpClient = HttpClients.createDefault();try {HttpPost post = new HttpPost(requestPath);FileInputStream fileInputStream = new FileInputStream("d:/a.jpg");post.setEntity(new InputStreamEntity(fileInputStream));CloseableHttpResponse response = httpClient.execute(post);System.out.println("upload返回状态:" + response.getStatusLine());HttpEntity responseEntity = response.getEntity();System.out.println("upload返回结果:" + EntityUtils.toString(responseEntity));//流畅api调⽤String result = Request.Post(requestPath).bodyStream(new FileInputStream("d:/a.jpg")).execute().returnContent().asString(Charset.forName("utf-8"));System.out.println("upload fluent返回结果:" + result);} catch (Exception e) {e.printStackTrace();} finally {close(httpClient);}}2.5、上传⽂件及发送键值对数据public static void multi() {String requestPath = "http://localhost:8080/demo/httptest/multi";CloseableHttpClient httpClient = HttpClients.createDefault();try {HttpPost post = new HttpPost(requestPath);FileBody file = new FileBody(new File("d:/a.jpg"));HttpEntity requestEntity = MultipartEntityBuilder.create().addPart("file", file).addPart("param1", new StringBody("参数1", ContentType.create(ContentType.TEXT_PLAIN.getMimeType(), "utf-8"))) .addPart("param2", new StringBody("参数2", ContentType.create(ContentType.TEXT_PLAIN.getMimeType(), "utf-8"))) .build();post.setEntity(requestEntity);CloseableHttpResponse response = httpClient.execute(post);System.out.println("multi返回状态:" + response.getStatusLine());HttpEntity responseEntity = response.getEntity();System.out.println("multi返回结果:" + EntityUtils.toString(responseEntity));//流畅api调⽤String result = Request.Post(requestPath).body(MultipartEntityBuilder.create().addPart("file", file).addPart("param1", new StringBody("参数1", ContentType.create(ContentType.TEXT_PLAIN.getMimeType(), "utf-8"))) .addPart("param2", new StringBody("参数2", ContentType.create(ContentType.TEXT_PLAIN.getMimeType(), "utf-8"))) .build()).execute().returnContent().asString(Charset.forName("utf-8"));System.out.println("multi fluent返回结果:" + result);} catch (Exception e) {e.printStackTrace();} finally {close(httpClient);}}2.6、完整例⼦package com.inspur.demo.http.client;import java.io.File;import java.io.FileInputStream;import java.io.IOException;import java.nio.charset.Charset;import java.util.ArrayList;import java.util.List;import org.apache.http.HttpEntity;import ValuePair;import org.apache.http.client.entity.UrlEncodedFormEntity;import org.apache.http.client.fluent.Form;import org.apache.http.client.fluent.Request;import org.apache.http.client.methods.CloseableHttpResponse;import org.apache.http.client.methods.HttpGet;import org.apache.http.client.methods.HttpPost;import org.apache.http.entity.ContentType;import org.apache.http.entity.InputStreamEntity;import org.apache.http.entity.StringEntity;import org.apache.http.entity.mime.MultipartEntityBuilder;import org.apache.http.entity.mime.content.FileBody;import org.apache.http.entity.mime.content.StringBody;import org.apache.http.impl.client.CloseableHttpClient;import org.apache.http.impl.client.HttpClients;import org.apache.http.message.BasicNameValuePair;import org.apache.http.util.EntityUtils;/*** 通过HttpClient调⽤Http接⼝*/public class HttpClientCase {/*** GET请求*/public static void get() {String requestPath = "http://localhost:8080/demo/httptest/getUser?userId=1000&userName=李⽩";CloseableHttpClient httpClient = HttpClients.createDefault();try {HttpGet get = new HttpGet(requestPath);CloseableHttpResponse response = httpClient.execute(get);System.out.println("GET返回状态:" + response.getStatusLine());HttpEntity responseEntity = response.getEntity();System.out.println("GET返回结果:" + EntityUtils.toString(responseEntity));//流畅api调⽤String result = Request.Get(requestPath).execute().returnContent().asString(Charset.forName("utf-8"));System.out.println("GET fluent返回结果:" + result);} catch (Exception e) {e.printStackTrace();} finally {close(httpClient);}}/*** POST请求(发送键值对数据)*/public static void post() {String requestPath = "http://localhost:8080/demo/httptest/getUser";CloseableHttpClient httpClient = HttpClients.createDefault();try {HttpPost post = new HttpPost(requestPath);List<NameValuePair> list = new ArrayList<NameValuePair>();list.add(new BasicNameValuePair("userId", "1000"));list.add(new BasicNameValuePair("userName", "李⽩"));post.setEntity(new UrlEncodedFormEntity(list, "utf-8"));CloseableHttpResponse response = httpClient.execute(post);System.out.println("POST返回状态:" + response.getStatusLine());HttpEntity responseEntity = response.getEntity();System.out.println("POST返回结果:" + EntityUtils.toString(responseEntity));//流畅api调⽤String result = Request.Post(requestPath).bodyForm(Form.form().add("userId", "1000").add("userName", "李⽩").build(), Charset.forName("utf-8")) .execute().returnContent().asString(Charset.forName("utf-8"));System.out.println("POST fluent返回结果:" + result);} catch (Exception e) {e.printStackTrace();} finally {close(httpClient);}}/*** POST请求(发送json数据)*/public static void post2() {String requestPath = "http://localhost:8080/demo/httptest/addUser";CloseableHttpClient httpClient = HttpClients.createDefault();try {HttpPost post = new HttpPost(requestPath);post.setHeader("Content-type", "application/json");String param = "{\"userId\": \"1001\",\"userName\":\"杜甫\"}";post.setEntity(new StringEntity(param, "utf-8"));CloseableHttpResponse response = httpClient.execute(post);System.out.println("POST json返回状态:" + response.getStatusLine());HttpEntity responseEntity = response.getEntity();System.out.println("POST josn返回结果:" + EntityUtils.toString(responseEntity));//流畅api调⽤String result = Request.Post(requestPath).addHeader("Content-type", "application/json").bodyString(param, ContentType.APPLICATION_JSON).execute().returnContent().asString(Charset.forName("utf-8"));System.out.println("POST json fluent返回结果:" + result);} catch (Exception e) {e.printStackTrace();} finally {close(httpClient);}}/*** 上传⽂件*/public static void upload() {String requestPath = "http://localhost:8080/demo/httptest/upload";CloseableHttpClient httpClient = HttpClients.createDefault();try {HttpPost post = new HttpPost(requestPath);FileInputStream fileInputStream = new FileInputStream("d:/a.jpg");post.setEntity(new InputStreamEntity(fileInputStream));CloseableHttpResponse response = httpClient.execute(post);System.out.println("upload返回状态:" + response.getStatusLine());HttpEntity responseEntity = response.getEntity();System.out.println("upload返回结果:" + EntityUtils.toString(responseEntity));//流畅api调⽤String result = Request.Post(requestPath).bodyStream(new FileInputStream("d:/a.jpg")).execute().returnContent().asString(Charset.forName("utf-8"));System.out.println("upload fluent返回结果:" + result);} catch (Exception e) {e.printStackTrace();} finally {close(httpClient);}}/*** 上传⽂件及发送键值对数据*/public static void multi() {String requestPath = "http://localhost:8080/demo/httptest/multi";CloseableHttpClient httpClient = HttpClients.createDefault();try {HttpPost post = new HttpPost(requestPath);FileBody file = new FileBody(new File("d:/a.jpg"));HttpEntity requestEntity = MultipartEntityBuilder.create().addPart("file", file).addPart("param1", new StringBody("参数1", ContentType.create(ContentType.TEXT_PLAIN.getMimeType(), "utf-8"))) .addPart("param2", new StringBody("参数2", ContentType.create(ContentType.TEXT_PLAIN.getMimeType(), "utf-8"))) .build();post.setEntity(requestEntity);CloseableHttpResponse response = httpClient.execute(post);System.out.println("multi返回状态:" + response.getStatusLine());HttpEntity responseEntity = response.getEntity();System.out.println("multi返回结果:" + EntityUtils.toString(responseEntity));//流畅api调⽤String result = Request.Post(requestPath).body(MultipartEntityBuilder.create().addPart("file", file).addPart("param1", new StringBody("参数1", ContentType.create(ContentType.TEXT_PLAIN.getMimeType(), "utf-8"))) .addPart("param2", new StringBody("参数2", ContentType.create(ContentType.TEXT_PLAIN.getMimeType(), "utf-8"))).build()).execute().returnContent().asString(Charset.forName("utf-8"));System.out.println("multi fluent返回结果:" + result);} catch (Exception e) {e.printStackTrace();} finally {close(httpClient);}}private static void close(CloseableHttpClient httpClient) {try {if (httpClient != null) {httpClient.close();}} catch (IOException e) {e.printStackTrace();}}public static void main(String[] args) {get();post();post2();upload();multi();}}View Code3、调⽤Https接⼝与调⽤Http接⼝不⼀样的部分主要在设置ssl部分,其ssl的设置与HttpsURLConnection很相似(参见);下⾯⽤GET请求来演⽰ssl的设置,其他调⽤⽅式类似。
httpclient
Header locationHeader = postMethod.getResponseHeader("location");
String location = null;
if (locationHeader != null) {
//执行getMethod
int statusCode = client.executeMethod(getMethod);
if (statusCode != HttpStatus.SC_OK) {
System.err.println("Method failed: " + getMethod.getStatusLine());
System.out.println(new String(responseBody));
下面是程序的完整代码,这些代码也可在附件中的test.GetSample中找到。
package test;
import java.io.IOException;
import mons.httpclient.*;
? 创建GET方法的实例。在GET方法的构造函数中传入待连接的地址即可。用GetMethod将会自动处理转发过程,如果想要把自动处理转发过程去掉的话,可以调用方法setFollowRedirects(false)。
GetMethod getMethod = new GetMethod("/");
// HttpClient对于要求接受后继服务的请求,象POST和PUT等不能自动处理转发
// 301或者302
if (statusCode == HttpStatus.SC_MOVED_PERMANENTLY ||
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
【Android进阶学习】Http编程之HttpClient 在Android开发中,Android SDK附带了Apache的HttpClient,它是一个完善的客户端。
它提供了对HTTP协议的全面支持,可以使用HttpClient的对象来执行HTTP GET和HTTP POST调用。
HTTP工作原理:1.客户端(一般是指浏览器,这里是指自己写的程序)与服务器建立连接2.建立连接后,客户端向服务器发送请求3.服务器接收到请求后,向客户端发送响应信息4.客户端与服务器断开连接HttpClient的一般使用步骤:1.使用DefaultHttpClient类实例化HttpClient对象2.如果要发送get请求,创建HttpGet对象,如果需要发送post请求,创建HttpPost对象。
3.如果需要发送请求参数,可以调用HttpGet、HttpPost共同的setParams(HttpParamsparams)方法来添加请求参数;对于HttpPost对象来说,也可以调用setEntity(HttpEntity entity)方法来设置请求参数。
3.调用HttpClient对象的execute(HttpUrlRequest request)方法发送HTTP GET或HTTP POST请求,并返回HttpResponse对象。
4.通过HttpResponse接口的getEntity方法可以获取HttpEntity对象,返回响应信息,并进行相应的处理。
最后记得要在AndroidManifest.xml文件添加网络权限<uses-permission android:name="android.permission.INTERNET" />下面是具体的例子:1.使用HttpClient来执行GET调用在LogCat窗口就能看到输出的信息1.package com.lingdududu.http;2.3.import java.io.InputStream;4.5.import org.apache.http.HttpResponse;6.import org.apache.http.HttpStatus;7.import org.apache.http.client.HttpClient;8.import org.apache.http.client.methods.HttpGet;9.import org.apache.http.impl.client.DefaultHttpClient;10.11.import android.app.Activity;12.import android.os.Bundle;13.import android.util.Log;14.15.public class HttpGetActivity extends Activity {16. String uri = "/";17.final String TAG_STRING = "TAG";18.@Override19.public void onCreate(Bundle savedInstanceState) {20.super.onCreate(savedInstanceState);21. setContentView(yout.main);22.23.try {24.//得到HttpClient对象25. HttpClient getClient = new DefaultHttpClient();26.//得到HttpGet对象27. HttpGet request = new HttpGet(uri);28.//客户端使用GET方式执行请教,获得服务器端的回应response29. HttpResponse response = getClient.execute(request);30.//判断请求是否成功31.if(response.getStatusLine().getStatusCode()==HttpStatus.SC_OK){32. Log.i(TAG_STRING, "请求服务器端成功");33.//获得输入流34. InputStream inStrem = response.getEntity().getContent();35.int result = inStrem.read();36.while (result != -1){37. System.out.print((char)result);38. result = inStrem.read();39. }40.//关闭输入流41. inStrem.close();42. }else {43. Log.i(TAG_STRING, "请求服务器端失败");44. }45. } catch (Exception e) {46.// TODO Auto-generated catch block47. e.printStackTrace();48. }49. }50.}使用HTTP GET调用有一个缺点就是,请求的参数作为URL一部分来传递,以这种方式传递的时候,URL的长度应该在2048个字符之内。
如果超出这个这范围,就要使用到HTTP POST 调用。
2.使用HttpClient来执行POST调用使用POST调用进行参数传递时,需要使用NameValuePair来保存要传递的参数。
NameValuePair封装了一个键/值组合。
另外,还需要设置所使用的字符集。
1.package com.androidbook.services.httppost;2.3.import java.io.BufferedReader;4.import java.io.IOException;5.import java.io.InputStreamReader;6.import java.util.ArrayList;7.import java.util.List;8.9.import org.apache.http.HttpResponse;10.import ValuePair;11.import org.apache.http.client.HttpClient;12.import org.apache.http.client.entity.UrlEncodedFormEntity;13.import org.apache.http.client.methods.HttpPost;14.import org.apache.http.impl.client.DefaultHttpClient;15.import org.apache.http.message.BasicNameValuePair;16.17.import android.app.Activity;18.import android.os.Bundle;19.20.public class HttpPostActivity extends Activity {21. String uri = "/";22.@Override23.public void onCreate(Bundle savedInstanceState) {24.super.onCreate(savedInstanceState);25. setContentView(yout.main);26.27. BufferedReader in = null;28.try {29. HttpClient client = new DefaultHttpClient();30. HttpPost request = new HttpPost("http://code.google.com/android/");31.//使用NameValuePair来保存要传递的Post参数32. List<NameValuePair> postParameters = new ArrayList<NameValuePair>();33.//添加要传递的参数34. postParameters.add(new BasicNameValuePair("id", "12345"));35. postParameters.add(new BasicNameValuePair("username","dave"));36.//实例化UrlEncodedFormEntity对象37. UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(38. postParameters);39.40.//使用HttpPost对象来设置UrlEncodedFormEntity的Entity41. request.setEntity(formEntity);42. HttpResponse response = client.execute(request);43. in = new BufferedReader(44.new InputStreamReader(45. response.getEntity().getContent()));46.47. StringBuffer string = new StringBuffer("");48. String lineStr = "";49.while ((lineStr = in.readLine()) != null) {50. string.append(lineStr + "\n");51. }52. in.close();53.54. String resultStr = string.toString();55. System.out.println(resultStr);56. } catch(Exception e) {57.// Do something about exceptions58. } finally {59.if (in != null) {60.try {61. in.close();62. } catch (IOException e) {63. e.printStackTrace();64. }65. }66. }67. }68.}。