HttpClient方式调用接口的实例

本文介绍了使用httpClient调用https接口、上传文件的方法。包含调用https接口的代码实现,接口层写法及测试示例;还给出了上传文件时pom.xml的依赖引入和文件上传接口代码,以及另一种调用https接口的方式和后端定义接口为list对象参数时的httpClient调用方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

第一种:调用https接口

/**
     * 
     * @Title: postSmart @Description: TODO( ) @param
     * strURL @param param @return 參數描述 @return ResultCommonDTO<String> 返回类型 @throws
     */
    public static String postSmart(String strURL, String params) {
        PostMethod postMethod = null;
        HttpClient httpclient = null;
        try {
            // 把事例代码中的第一行实例化代码改为如下即可,在postMethod.releaseConnection();之后connection manager会关闭
            httpclient = new HttpClient(new HttpClientParams(), new SimpleHttpConnectionManager());
            postMethod = new PostMethod(strURL);
            // postMethod.setRequestHeader("Content-Type",
            // "application/x-www-form-urlencoded;charset=gbk");
            // 设置编码方式
            postMethod.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");

            //设置参数

           postMethod.addParameter("params", params);
            // 执行请求
            httpclient.executeMethod(postMethod);
            String info = new String(postMethod.getResponseBody(), "UTF-8");
            return info ;
        } catch (IOException e) {
            return null ;
        } finally {
            // 关闭连接,释放资源
            postMethod.releaseConnection();

        }
    }
 

接口层写法

@Controller
@RequestMapping("/nav")
public class TestController {
    @RequestMapping("/test")
    @ResponseBody
    public String testNav(@RequestParam String params){

        System.out.print(params);
        return params;

    }
}

测试接口:

public static void main(String[] args)  {
        String url = "http://localhost:8888/nav/test";
        JSONObject obj = new JSONObject();
        obj.put("aaa", "aaa");
        obj.put("bbb", "bbb");
        obj.put("uuid", "E01DD2F4F1B947AC8CBD53291FE87A7C");
        obj.put("ccc", "ccccc");
        String info =  HttpUtil.postSmart(url, obj.toString());
        System.out.println(info);

    }

调用上传文件

pom.xml引入

<!-- http包 -->

                   <dependency>

                            <groupId>org.apache.httpcomponents</groupId>

                            <artifactId>httpclient</artifactId>

                   </dependency>

                   <dependency>

                            <groupId>org.apache.httpcomponents</groupId>

                            <artifactId>httpmime</artifactId>

                   </dependency>

                   <dependency>

                            <groupId>org.apache.httpcomponents</groupId>

                            <artifactId>httpcore</artifactId>

                   </dependency>

                <!-- http包 -->

/**
     * 文件上传接口
     * @param url
     * @param files
     * @param username
     * @return
     * @throws IOException
     */
    public static String  floorSSOHttpFile(String url, MultipartFile[] files,String username) throws IOException{
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        MultipartEntityBuilder entity = MultipartEntityBuilder.create();
        HttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);
        
        for(MultipartFile f : files){
            String fileName = f.getOriginalFilename();
            entity.addBinaryBody("files", f.getInputStream(), ContentType.MULTIPART_FORM_DATA, fileName);
        }
        //设置参数
        entity.addTextBody("user", username);
        entity.addTextBody("type", "PC");
        entity.addTextBody("datetime",sdf.format(new Date()));
        entity.addTextBody("project","Mascot");
        //entity.addTextBody("name",name);
        String result = null;
        httpPost.setEntity(entity.build());
        HttpResponse httpResponse = httpClient.execute(httpPost);
        int code = httpResponse.getStatusLine().getStatusCode();
        if(code == 200){
            String returnStr = EntityUtils.toString(httpResponse.getEntity(),HTTP.UTF_8);
            JSONObject jsonObject = JSONObject.fromObject(returnStr);
            //System.out.println(jsonObject.get("url"));
            return (String) jsonObject.get("url");
        }else
            System.out.println(EntityUtils.toString(httpResponse.getEntity()));
        return result;
    }

第二种调用https:

public static ResultCommonDTO<String> postSmart(String strURL, String params,
      String headerValue) {
    URL url = null;
    HttpsURLConnection connection = null;
    try {
      TrustManager[] trustAllCerts = new TrustManager[1];
      TrustManager tm = new MyX509TrustManager();
      trustAllCerts[0] = tm;
      javax.net.ssl.SSLContext sc = javax.net.ssl.SSLContext.getInstance("SSL");
      sc.init(null, trustAllCerts, new java.security.SecureRandom());
      SSLSocketFactory ssf = sc.getSocketFactory();
      try {

        // 打开于URL之间的连接

        url = new URL(strURL);
        connection = (HttpsURLConnection) url.openConnection();
        connection.setSSLSocketFactory(ssf);
        connection.setDoOutput(true);
        connection.setDoInput(true);
        connection.setUseCaches(false);
        connection.setInstanceFollowRedirects(true);
        // connection.setConnectTimeout(1000000);
        // connection.setReadTimeout(2000000);

        connection.setConnectTimeout(300000);
        connection.setReadTimeout(300000);
        // 设置请求方式
        connection.setRequestMethod("POST");
        // 设置接收数据的格式
        connection.setRequestProperty("Accept", "application/json");
        // 设置发送数据的格式
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setRequestProperty("x-accesskey", headerValue);
        connection.connect();// 连接
        OutputStreamWriter out = new OutputStreamWriter(
            // 获得URL connection对象对应的输出流
            connection.getOutputStream(), "UTF-8");
        // 添加请求参数
        out.append(params);
        out.flush();
        out.close();
        // 读取响应
        BufferedReader reader = new BufferedReader(new InputStreamReader(
            // 定义BufferReader输入流来读取URL的相应
            connection.getInputStream()));
        String lines;
        StringBuilder sb = new StringBuilder(64);
        while ((lines = reader.readLine()) != null) {
          lines = new String(lines.getBytes(), "utf-8");
          sb.append(lines);
        }
        reader.close();
        return new ResultCommonDTO<String>(true, null, sb.toString());
      } catch (IOException e) {
        return new ResultCommonDTO<>(false, "POST资源失败:" + e.getMessage(), null);
      } finally {
        if (connection != null) {
          connection.disconnect();
        }
      }
    } catch (Exception e) {
      return new ResultCommonDTO<>(false, "POST资源失败:" + e.getMessage(), null);
    }
  }

2、后端定义接口是list对象参数

/**
 * 修改保存试乘试驾车状态同步
 */
@PostMapping("/vehicleSync")
@ApiOperation("试乘试驾车状态同步接口")
@ResponseBody
public R editSave(@Validated @RequestBody List<@Valid Vehicle> vehicles) {
    if(StringUtils.isNull(vehicles)){
        return R.error("数据不能为空");
    }
    log.info("【TbDriveVehicleStatusController -- editSave】传入的需要处理车辆数据,数据大小:{},入参的参数数据:{}",vehicles.size(),vehicles.toString());
    //返回给调用接口集合
    List<Vehicle>   resultList=  new ArrayList<>();
    // 保存数据的list
    List<Vehicle>   saveList=  new ArrayList<>();
    for(Vehicle vehicle : vehicles){
        R result = ParameterUtil.isParameter(vehicle);
        if(result.get("code").equals(RStatus.fail.getCode())){
            log.error("【TbDriveVehicleStatusController -- editSave】传入的需要处理车辆数据有空,入参的参数数据:{},消息的提醒:{}",vehicle.toString(),result.get("msg"));
            resultList.add(vehicle);
        }else {
            saveList.add(vehicle);
        }
    }

    if(saveList != null && saveList.size() > 0){
        log.info("【TbDriveVehicleStatusController -- editSave】插入的需要处理车辆数据,数据大小:{},插入数据表的数据:{},",saveList.size(),saveList.toString());
        tbDriveVehicleStatusService.updateTbDriveVehicleList(saveList);
    }

    if(resultList != null && resultList.size() > 0){
        return R.error("参数错误",resultList);
    }

    return R.success();
}

httpClient调用方法,

引用jar

<dependency>
   <groupId>org.apache.httpcomponents</groupId>
   <artifactId>httpclient</artifactId>
   <version>4.5.2</version>
</dependency>
定义方法:
/**
 *
 * @param url
 * @param json  参数可以 list对象, 转成json 格式
 * @return
 * @throws Exception
 */
public static String sendHttpPost(String url, String json) throws Exception {
    CloseableHttpClient httpClient = HttpClients.createDefault();
    HttpPost httpPost = new HttpPost(url);
    httpPost.addHeader("Content-Type", "application/json");
    httpPost.setEntity(new StringEntity(json,"UTF-8"));
    CloseableHttpResponse response = httpClient.execute(httpPost);
    HttpEntity entity = response.getEntity();
    String responseContent = EntityUtils.toString(entity, "UTF-8");
    response.close();
    httpClient.close();
    return responseContent;
}

测试接口

@Deprecated
@PostMapping("/test")
@ApiOperation("test参数是list对象接口")
@ResponseBody
public R test() throws Exception {
    List<Vehicle> vehicles =new ArrayList<>();
    Vehicle vehicle = new Vehicle();

    vehicle.setStatus(1);
    vehicle.setVin("1234567");
    vehicles.add(vehicle);
    vehicle = new Vehicle();
    vehicle.setStatus(2);
    vehicle.setVin("987654321");
    vehicles.add(vehicle);
    String s = JSONObject.toJSONString(vehicles);

    String result = HttpUtils.sendHttpPost("http://localhost:8099/lion-driving-server/driving/vehicle/vehicleSync", s);

    System.out.println("返回的值result:"+result);
    JSONObject object = JSONObject.parseObject(result);
    System.out.println("返回的值:"+object.toString());
    return R.success();
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值