HttpClient 4.0 post file and text

本文介绍如何使用 HttpClient 4.0 进行 POST 请求,并附带上传文件的功能。通过示例代码展示了如何配置 HttpClient 和 HttpPost,以及如何处理请求参数和文件上传。

HttpClient 4.0 实例--简单工具类

一、基于Maven项目前期准备

    1、所需jar包,本人使用的Maven项目,其中Pom.xml内容如下所示

<dependency>
      <groupId>org.apache.httpcomponents</groupId>
      <artifactId>httpmime</artifactId>
      <version>4.3.4</version>
</dependency>

      其中4.3.4只是随意使用的一个版本(只要使用4.0以上版本即可),其中所依赖的

    客户端代码:

package com.xxx.test;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
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.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

public class HttpClientText {

	/**
	 * HTTPCLIENT 4.0 POST 另外一种访问方式
	 */
	@SuppressWarnings({ "deprecation", "resource" })
	public static void postForm() {
		try {
			// 定义 httpclient链接
			HttpClient httpclient = new DefaultHttpClient();
			// Post 访问提交方式
			HttpPost httppost = new HttpPost("URL 地址");
			//HttpGet httpGet =  new HttpGet("URL 地址");
			
			// 设置请求参数信息request params信息 --- 参数集合信息
			List<NameValuePair> nvps = new ArrayList<NameValuePair>();
			nvps.add(new BasicNameValuePair("参数名", "参数值"));

			// 将参数赋值到请求参数实体信息 ---并使用指定参数的编码格式 对参数转码 转义
			httppost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
			// 发起会话请求获取访问结果
			HttpResponse response = httpclient.execute(httppost);
			//HttpResponse response = httpclient.execute(httpGet);
			
			// 读取请求返回结果 实体信息
			HttpEntity entity = response.getEntity();
			// 返回结果实体Body信息
			String body = EntityUtils.toString(entity);
			System.err.println(body);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * HTTPCLIENT 4.0 POST 带附件File请求
	 */
	@SuppressWarnings({ "deprecation", "resource" })
	public static void uploadFilePost() {
		try {
			// 定义 httpclient链接
			HttpClient httpclient = new DefaultHttpClient();
			// Post 访问提交方式
			HttpPost httppost = new HttpPost("URL 地址");
			// 设置请求超时时间
			httpclient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 50000);
			// 设置读取超时时间
			httpclient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 50000);

			// 设置请求参数信息request params信息 --- 参数生成器
			MultipartEntityBuilder build = MultipartEntityBuilder.create();
			// ContentType 指定参数编码格式、解析方式 包含多种格式 例如: "text/html",
			// Consts.ISO_8859_1 等
			build.addPart("appid:参数名称", new StringBody("参数值", ContentType.DEFAULT_TEXT));
			// 将文件流对象写入到请求request中
			build.addBinaryBody("imageFile:参数名", new File("附件地址"));

			// 将参数赋值到请求参数实体信息
			httppost.setEntity(build.build());
			// 发起会话请求获取访问结果
			HttpResponse response = httpclient.execute(httppost);
			// 读取请求返回结果 实体信息
			HttpEntity entity = response.getEntity();
			// 返回结果实体Body信息
			String body = EntityUtils.toString(entity);
			System.err.println(body);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
 

      基于SPRING MVC 实现的服务端代码,如下所示(仅给出包含File参数的服务端代码):

  

@RequestMapping(value = "xxx/upload_file", method = RequestMethod.POST)
public String uploadFile(String appid, MultipartFile imageFile, Model model) {
     ......
}

 

 

PS C:\Users\Administrator> # 加载必要程序集 - 确保使用正确的方法 PS C:\Users\Administrator> Add-Type -AssemblyName System.Net.Http -ErrorAction Stop PS C:\Users\Administrator> PS C:\Users\Administrator> function Invoke-EnhancedCurlRequest { >> [CmdletBinding()] >> param( >> [Parameter(Mandatory=$true)] >> [string]$Uri, >> [ValidateSet('GET','POST','PUT','DELETE','PATCH','HEAD','OPTIONS')] >> [string]$Method = 'GET', >> [hashtable]$Headers = @{}, >> [object]$Body, >> [int]$Timeout = 30, >> [switch]$SkipCertificateCheck, >> [switch]$UseGzipCompression >> ) >> >> $resultTemplate = [PSCustomObject]@{ >> StatusCode = 0 >> StatusMessage = "NotExecuted" >> Headers = [ordered]@{} >> Content = $null >> IsSuccess = $false >> Technology = "None" >> ErrorMessage = $null >> ElapsedMs = 0 >> } >> >> $timer = [System.Diagnostics.Stopwatch]::StartNew() >> $result = $resultTemplate.PSObject.Copy() >> $result.Technology = "HttpClient" >> >> try { >> $handler = New-Object System.Net.Http.HttpClientHandler >> >> # 修复证书验证 - 兼容旧版 .NET >> if ($SkipCertificateCheck) { >> $handler.ServerCertificateCustomValidationCallback = { >> param($sender, $cert, $chain, $sslPolicyErrors) >> return $true >> } >> } >> >> if ($UseGzipCompression) { >> $handler.AutomaticDecompression = [System.Net.DecompressionMethods]::GZip >> } >> >> $client = New-Object System.Net.Http.HttpClient($handler) >> $client.Timeout = [System.TimeSpan]::FromSeconds($Timeout) >> >> $request = New-Object System.Net.Http.HttpRequestMessage( >> [System.Net.Http.HttpMethod]::Parse($Method), >> $Uri >> ) >> >> # 添加默认 User-Agent >> if (-not $Headers.ContainsKey('User-Agent')) { >> $request.Headers.TryAddWithoutValidation("User-Agent", "PowerShell-HTTPClient/1.0") >> } >> >> # 添加自定义头 >> foreach ($key in $Headers.Keys) { >> if (-not $request.Headers.TryAddWithoutValidation($key, $Headers[$key])) { >> if (-not $request.Content) { >> $request.Content = New-Object System.Net.Http.StringContent("") >> } >> $request.Content.Headers.TryAddWithoutValidation($key, $Headers[$key]) >> } >> } >> >> # 处理请求体 >> if ($Body -and @('POST','PUT','PATCH') -contains $Method) { >> if ($Body -is [byte[]]) { >> $request.Content = New-Object System.Net.Http.ByteArrayContent($Body) >> } >> elseif ($Body -is [hashtable] -or $Body -is [System.Collections.IDictionary]) { >> $jsonBody = $Body | ConvertTo-Json -Depth 5 -Compress >> $request.Content = New-Object System.Net.Http.StringContent( >> $jsonBody, >> [System.Text.Encoding]::UTF8, >> "application/json" >> ) >> } >> elseif ($Body -is [string]) { >> $request.Content = New-Object System.Net.Http.StringContent( >> $Body, >> [System.Text.Encoding]::UTF8 >> ) >> } >> else { >> throw "Unsupported body type: $($Body.GetType().Name)" >> } >> } >> >> # 发送请求 >> $response = $client.SendAsync($request).GetAwaiter().GetResult() >> >> # 解析响应 >> $result.StatusCode = [int]$response.StatusCode >> $result.StatusMessage = $response.ReasonPhrase >> $result.IsSuccess = $response.IsSuccessStatusCode >> >> $result.Headers = [ordered]@{} >> foreach ($header in $response.Headers) { >> $result.Headers[$header.Key] = $header.Value -join ", " >> } >> >> foreach ($header in $response.Content.Headers) { >> $result.Headers[$header.Key] = $header.Value -join ", " >> } >> >> $result.Content = $response.Content.ReadAsStringAsync().GetAwaiter().GetResult() >> return $result >> } >> catch [System.Threading.Tasks.TaskCanceledException] { >> $result.ErrorMessage = "Request timed out after $Timeout seconds" >> $result.StatusCode = 408 >> $result.StatusMessage = "Timeout" >> return $result >> } >> catch { >> # 提供更详细的错误信息 >> $result.ErrorMessage = $_.Exception.ToString() >> $result.StatusCode = 500 >> $result.StatusMessage = "HttpRequestError" >> return $result >> } >> finally { >> $timer.Stop() >> $result.ElapsedMs = $timer.ElapsedMilliseconds >> >> # 清理资源 >> if ($response) { $response.Dispose() } >> if ($request) { $request.Dispose() } >> if ($client) { $client.Dispose() } >> if ($handler) { $handler.Dispose() } >> } >> } >> PS C:\Users\Administrator> $handler.ServerCertificateCustomValidationCallback = { >> param($sender, $cert, $chain, $sslPolicyErrors) >> return $true >> } >> 在此对象上找不到属性“ServerCertificateCustomValidationCallback”。请确认该属性存在并且可设置。 所在位置 行:1 字符: 1 + $handler.ServerCertificateCustomValidationCallback = { + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : InvalidOperation: (:) [],RuntimeException + FullyQualifiedErrorId : PropertyNotFound PS C:\Users\Administrator> $handler.ServerCertificateCustomValidationCallback = { >> param($sender, $cert, $chain, $sslPolicyErrors) >> return $true >> } >> 在此对象上找不到属性“ServerCertificateCustomValidationCallback”。请确认该属性存在并且可设置。 所在位置 行:1 字符: 1 + $handler.ServerCertificateCustomValidationCallback = { + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : InvalidOperation: (:) [],RuntimeException + FullyQualifiedErrorId : PropertyNotFound PS C:\Users\Administrator> $request.Headers.TryAddWithoutValidation("User-Agent", "PowerShell-HTTPClient/1.0") 不能对 Null 值表达式调用方法。 所在位置 行:1 字符: 1 + $request.Headers.TryAddWithoutValidation("User-Agent", "PowerShell-HT ... + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : InvalidOperation: (:) [],RuntimeException + FullyQualifiedErrorId : InvokeMethodOnNull PS C:\Users\Administrator> $result.ErrorMessage = $_.Exception.ToString() 不能对 Null 值表达式调用方法。 所在位置 行:1 字符: 1 + $result.ErrorMessage = $_.Exception.ToString() + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : InvalidOperation: (:) [],RuntimeException + FullyQualifiedErrorId : InvokeMethodOnNull PS C:\Users\Administrator> if ($response) { $response.Dispose() } PS C:\Users\Administrator> # 创建模块目录 PS C:\Users\Administrator> $moduleDir = "$env:ProgramFiles\WindowsPowerShell\Modules\PSHttpClient" PS C:\Users\Administrator> New-Item -Path $moduleDir -ItemType Directory -Force | Out-Null PS C:\Users\Administrator> PS C:\Users\Administrator> # 生成并保存模块文件 PS C:\Users\Administrator> $fixedModuleCode = @' >> <上面修复后的完整函数代码> >> '@ >> $fixedModuleCode | Out-File "$moduleDir\PSHttpClient.psm1" -Encoding UTF8 -Force >> PS C:\Users\Administrator> # 重新加载模块 PS C:\Users\Administrator> Remove-Module PSHttpClient -ErrorAction SilentlyContinue PS C:\Users\Administrator> Import-Module PSHttpClient -Force -PassThru < : 无法将“<”项识别为 cmdlet、函数、脚本文件或可运行程序的名称。请检查名称的拼写,如果包括路径,请确保路径正确,然后 再试一次。 所在位置 C:\Program Files\WindowsPowerShell\Modules\PSHttpClient\PSHttpClient.psm1:1 字符: 1 + <上面修复后的完整函数代码> + ~ + CategoryInfo : ObjectNotFound: (<:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException ModuleType Version Name ExportedCommands ---------- ------- ---- ---------------- Script 1.3 PSHttpClient PS C:\Users\Administrator> # 测试基本GET请求 PS C:\Users\Administrator> $response = Invoke-EnhancedCurlRequest -Uri "https://httpbin.org/get" -Method GET PS C:\Users\Administrator> PS C:\Users\Administrator> if ($response.IsSuccess) { >> Write-Host "✅ 模块工作正常" -ForegroundColor Green >> $response.Content | ConvertFrom-Json >> } else { >> Write-Host "❌ 模块存在问题: $($response.ErrorMessage)" -ForegroundColor Red >> } >> ❌ 模块存在问题: System.Management.Automation.RuntimeException: 方法调用失败,因为 [System.Net.Http.HttpMethod] 不包含名为“Parse”的方法。 在 System.Management.Automation.ExceptionHandlingOps.CheckActionPreference(FunctionContext funcContext, Exception exception) 在 System.Management.Automation.Interpreter.ActionCallInstruction`2.Run(InterpretedFrame frame) 在 System.Management.Automation.Interpreter.EnterTryCatchFinallyInstruction.Run(InterpretedFrame frame) 在 System.Management.Automation.Interpreter.EnterTryCatchFinallyInstruction.Run(InterpretedFrame frame) PS C:\Users\Administrator> ✅ 模块工作正常 ✅ : 无法将“✅”项识别为 cmdlet、函数、脚本文件或可运行程序的名称。请检查名称的拼写,如果包括路径,请确保路径正确,然后 再试一次。 所在位置 行:1 字符: 1 + ✅ 模块工作正常 + ~ + CategoryInfo : ObjectNotFound: (✅:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException PS C:\Users\Administrator> PS C:\Users\Administrator> args : {} args : 无法将“args”项识别为 cmdlet、函数、脚本文件或可运行程序的名称。请检查名称的拼写,如果包括路径,请确保路径正确 ,然后再试一次。 所在位置 行:1 字符: 1 + args : {} + ~~~~ + CategoryInfo : ObjectNotFound: (args:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException PS C:\Users\Administrator> headers : @{Accept=*/*; Accept-Encoding=gzip, deflate, br; Host=httpbin.org; User-Agent=PowerShell-HTTPClient/1.0; 所在位置 行:1 字符: 31 + headers : @{Accept=*/*; Accept-Encoding=gzip, deflate, br; Host=httpb ... + ~ 哈希文本中的键后面缺少“=”运算符。 所在位置 行:1 字符: 31 + headers : @{Accept=*/*; Accept-Encoding=gzip, deflate, br; Host=httpb ... + ~ 哈希文本不完整。 所在位置 行:1 字符: 25 + headers : @{Accept=*/*; Accept-Encoding=gzip, deflate, br; Host=httpb ... + ~~~~~~ 哈希文本中不允许包含重复的键“Accept”。 + CategoryInfo : ParserError: (:) [], ParentContainsErrorRecordException + FullyQualifiedErrorId : MissingEqualsInHashLiteral PS C:\Users\Administrator> X-Amzn-Trace-Id=Root=1-66c8f1b5-1234567890abcdef12345678} 所在位置 行:1 字符: 67 + X-Amzn-Trace-Id=Root=1-66c8f1b5-1234567890abcdef12345678} + ~ 表达式或语句中包含意外的标记“}”。 + CategoryInfo : ParserError: (:) [], ParentContainsErrorRecordException + FullyQualifiedErrorId : UnexpectedToken PS C:\Users\Administrator> url : https://httpbin.org/get url : 无法将“url”项识别为 cmdlet、函数、脚本文件或可运行程序的名称。请检查名称的拼写,如果包括路径,请确保路径正确, 然后再试一次。 所在位置 行:1 字符: 1 + url : https://httpbin.org/get + ~~~ + CategoryInfo : ObjectNotFound: (url:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException PS C:\Users\Administrator> # 重新加载模块 PS C:\Users\Administrator> Remove-Module PSHttpClient -ErrorAction SilentlyContinue PS C:\Users\Administrator> Import-Module PSHttpClient -Force < : 无法将“<”项识别为 cmdlet、函数、脚本文件或可运行程序的名称。请检查名称的拼写,如果包括路径,请确保路径正确,然后 再试一次。 所在位置 C:\Program Files\WindowsPowerShell\Modules\PSHttpClient\PSHttpClient.psm1:1 字符: 1 + <上面修复后的完整函数代码> + ~ + CategoryInfo : ObjectNotFound: (<:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException PS C:\Users\Administrator> PS C:\Users\Administrator> # 测试用例 PS C:\Users\Administrator> $testCases = @( >> @{Url = "https://httpbin.org/get"; Method = "GET"; ExpectedCode = 200} >> @{Url = "https://httpbin.org/post"; Method = "POST"; Body = @{name="Test"}; ExpectedCode = 200} >> @{Url = "https://self-signed.badssl.com/"; Method = "GET"; SkipCertificateCheck = $true; ExpectedCode = 200} >> @{Url = "https://invalid.domain.abc/"; Method = "GET"; ExpectedCode = 0} >> ) >> PS C:\Users\Administrator> # 执行测试 PS C:\Users\Administrator> $results = foreach ($test in $testCases) { >> $params = @{ >> Uri = $test.Url >> Method = $test.Method >> } >> >> if ($test.Body) { $params['Body'] = $test.Body } >> if ($test.SkipCertificateCheck) { $params['SkipCertificateCheck'] = $true } >> >> $result = Invoke-EnhancedCurlRequest @params >> >> [PSCustomObject]@{ >> TestCase = $test.Url >> Method = $test.Method >> Status = if ($result.StatusCode -eq $test.ExpectedCode) { "✅ PASS" } else { "❌ FAIL" } >> StatusCode = $result.StatusCode >> Expected = $test.ExpectedCode >> Success = $result.IsSuccess >> Tech = $result.Technology >> Error = if ($result.ErrorMessage) { $result.ErrorMessage } else { "None" } >> Time = Get-Date -Format "HH:mm:ss" >> } >> } >> 方法调用失败,因为 [System.Management.Automation.PSCustomObject] 不包含名为“Dispose”的方法。 所在位置 行:114 字符: 26 + if ($response) { $response.Dispose() } + ~~~~~~~~~~~~~~~~~~~ + CategoryInfo : InvalidOperation: (Dispose:String) [],RuntimeException + FullyQualifiedErrorId : MethodNotFound 方法调用失败,因为 [System.Management.Automation.PSCustomObject] 不包含名为“Dispose”的方法。 所在位置 行:114 字符: 26 + if ($response) { $response.Dispose() } + ~~~~~~~~~~~~~~~~~~~ + CategoryInfo : InvalidOperation: (Dispose:String) [],RuntimeException + FullyQualifiedErrorId : MethodNotFound 方法调用失败,因为 [System.Management.Automation.PSCustomObject] 不包含名为“Dispose”的方法。 所在位置 行:114 字符: 26 + if ($response) { $response.Dispose() } + ~~~~~~~~~~~~~~~~~~~ + CategoryInfo : InvalidOperation: (Dispose:String) [],RuntimeException + FullyQualifiedErrorId : MethodNotFound 方法调用失败,因为 [System.Management.Automation.PSCustomObject] 不包含名为“Dispose”的方法。 所在位置 行:114 字符: 26 + if ($response) { $response.Dispose() } + ~~~~~~~~~~~~~~~~~~~ + CategoryInfo : InvalidOperation: (Dispose:String) [],RuntimeException + FullyQualifiedErrorId : MethodNotFound PS C:\Users\Administrator> # 显示结果 PS C:\Users\Administrator> $results | Format-Table -AutoSize TestCase Method Status StatusCode Expected Success Tech Error -------- ------ ------ ---------- -------- ------- ---- ----- https://httpbin.org/get GET ❌ FAIL 500 200 False HttpClient System.Management.Automation.Ru... https://httpbin.org/post POST ❌ FAIL 500 200 False HttpClient System.Management.Automation.Ru... https://self-signed.badssl.com/ GET ❌ FAIL 500 200 False HttpClient System.Management.Automation.Ru... https://invalid.domain.abc/ GET ❌ FAIL 500 0 False HttpClient System.Management.Automation.Ru... PS C:\Users\Administrator>
最新发布
08-17
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值