HttpClient调用接口传递文件参数

方法一:使用 org.apache.commons.httpclient;的HttpClient
  • 具体代码:
public Map<String, Object> officialOcrUpload(String filePath) {
        Map<String, Object> reContent = new HashMap<>();
        String soapResponseInfo = "";
        File targeFile = new File(filePath);
        HttpClient httpClient = new HttpClient();
        PostMethod postMethod = new PostMethod(OFFICIAL_ENDPOINT+"?bizType=tm");
        int state = 500;
        try {
            FilePart filePart = new FilePart(targeFile.getName(), targeFile);
            filePart.setContentType("multipart/form-data");
            filePart.setName("file");
            Part[] parts = {filePart};

            postMethod.setRequestEntity(new MultipartRequestEntity(parts, postMethod.getParams()));
            httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(Integer.valueOf(OFFICIAL_TIMEOUT));//设置连接超时
            state = httpClient.executeMethod(postMethod);
            if (state == HttpStatus.SC_OK) {
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(postMethod.getResponseBodyAsStream(), "utf-8"));
                String responseLine = "";
                while((responseLine = bufferedReader.readLine()) != null){
                    soapResponseInfo += responseLine;
                }
            }
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (HttpException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            reContent.put("status", state);
            reContent.put("body", soapResponseInfo);
            postMethod.releaseConnection();
            if (state == HttpStatus.SC_OK) {
                reContent = queryOfficalDoc(soapResponseInfo);
            }
        }
        return reContent;
    }
方法二:使用org.apache.http.impl.client;的HttpClient
<dependency>
          <groupId>org.apache.httpcomponents</groupId>
          <artifactId>httpmime</artifactId>
          <version>4.3</version>
        </dependency>

<dependency>
          <groupId>org.apache.httpcomponents</groupId>
          <artifactId>httpcore</artifactId>
          <version>4.4.6</version>
        </dependency>
  • 具体代码
public String officialFileUpload(String filepath){
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(OFFICIAL_ENDPOINT+"?bizType=tm");
        String result = "";
        try {
            FileBody bin = new FileBody(new File(filepath));
            MultipartEntityBuilder reqEntity = MultipartEntityBuilder.create();
            reqEntity.addPart("file", bin);
            HttpEntity httpEntity = reqEntity.build();
            httpPost.setEntity(httpEntity);
            HttpResponse response = httpClient.execute(httpPost);
            HttpEntity responseEntity = response.getEntity();
            if (responseEntity != null) {
                result = EntityUtils.toString(responseEntity, Charset.forName("UTF-8"));
            }
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            httpPost.releaseConnection();
        }
        return result;
    }

目录

### 如何使用 HttpClient 调用第三方 API 接口 在 C# 中,`HttpClient` 类提供了异步发送 HTTP 请求的功能。下面展示了一个简单的例子,说明怎样通过 `HttpClient` 来调用第三方 Web API 并处理返回的数据。 #### 创建并配置 HttpClient 实例 为了提高性能和资源利用率,在应用程序生命周期内应该重用同一个 `HttpClient` 实例而不是每次请求都创建新的实例[^1]: ```csharp using System; using System.Net.Http; using System.Threading.Tasks; public class ApiClient { private static readonly HttpClient client = new HttpClient(); public ApiClient() { // 设置默认请求头, 如果需要的话可以在此处设置认证信息或者其他公共头部信息. client.DefaultRequestHeaders.Add("Accept", "application/json"); } } ``` #### 发送 GET 请求到第三方 API 当准备向特定 URL 发起 GET 请求时,可以通过如下方式完成操作,并读取响应内容作为 JSON 字符串[^2]: ```csharp public async Task<string> GetAsync(string url) { HttpResponseMessage response = await client.GetAsync(url); response.EnsureSuccessStatusCode(); // 抛出异常如果状态码不是成功系列 string responseBody = await response.Content.ReadAsStringAsync(); return responseBody; // 返回JSON字符串形式的结果 } ``` #### 处理 POST 请求以及提交数据给第三方服务 对于需要传递参数的情况,比如执行登录或者上传文件等场景,则可能需要用到 POST 方法。此时应当构建合适的 HttpContent 对象来携带要发送的信息[^3]: ```csharp public async Task<HttpResponseMessage> PostJsonAsync<T>(string url, T data) where T : class { var jsonContent = new StringContent( Newtonsoft.Json.JsonConvert.SerializeObject(data), Encoding.UTF8, "application/json" ); HttpResponseMessage response = await client.PostAsync(url, jsonContent); return response; } ``` 以上展示了基本的模式用于发起不同类型的 HTTP 请求至远程服务器上的 RESTful APIs 或者其他基于 HTTP 的 web services。实际应用中还需要考虑错误处理机制、超时控制等因素以确保程序健壮性和用户体验良好。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值