HttpUtils接口调用

 注入RestTemplate
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;

@Configuration
public class RestTemplateConfig {

    @Bean
    public RestTemplate restTemplate(RestTemplateBuilder builder) {
        return builder.build();
    }
}
1、get请求:
public static String doGet(String url, String token) {
    log.info("http请求:" + url);
    CloseableHttpClient client = HttpClients.createDefault();
    HttpGet get = new HttpGet(url);
    JSONObject response = null;
    get.addHeader("token", token);
    try {
        //设置请求和传输超时时间
        RequestConfig requestConfig =        RequestConfig.custom().setSocketTimeout(5000).setConnectTimeout(3000).build();
        get.setConfig(requestConfig);
        HttpResponse res = client.execute(get);
        log.info("http响应code:" + res.getStatusLine().getStatusCode());
        String result = EntityUtils.toString(res.getEntity());// 返回json格式:
        response = JSONObject.parseObject(result);
        log.info("http响应结果:" + response);
        return response.toString();
    } catch (Exception e) {
        log.error("接口请求异常", e);
    }
    return "";
}

2、post请求
 public static JSONObject httpPost(String url, JSONObject json, String token) {
        CloseableHttpClient client = HttpClients.createDefault();
        HttpPost post = new HttpPost(url);
        JSONObject response = null;
        // Create a header for the authorization token
        post.addHeader("token", token); 
        try {
            StringEntity s = new StringEntity(json.toString(), "utf-8");//解决中文乱码问题
            s.setContentEncoding("UTF-8");
            s.setContentType("application/json");//发送json数据需要设置contentType
            post.setEntity(s);
            HttpResponse res = client.execute(post);
            if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
//                 HttpEntity entity = res.getEntity();
                String result = EntityUtils.toString(res.getEntity());// 返回json格式:
                response = JSONObject.parseObject(result);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return response;
    }
3、文件上传(form_data)
public String fileUpload(Path filePath, String token) {
    try {
        String url = host + "/api"; // 替换为实际的API地址
        // 创建请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);
        headers.add("token", token);
        // 创建请求体
        MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
        // 添加文件参数
        FileSystemResource file = new FileSystemResource(filePath); // 本地文件路径
        body.add("file", file);
        // 创建HTTP请求实体
        HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(body, headers);
        try {
            // 发送POST请求
            ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.POST, requestEntity, String.class);
            if (response.getStatusCode().is2xxSuccessful()) {
                // 请求成功,可以处理响应数据
                JSONObject responseBody = JSONObject.parseObject(response.getBody());
                if (response.getStatusCodeValue() == HttpStatus.SUCCESS) {
                    JSONArray dataArray = responseBody.getJSONArray("data");
                    if (dataArray != null && dataArray.size() > 0) {
                        return dataArray.getString(0);
                    } else {
                        return null;
                    }
                } else {
                    return null;
                }
            } else {
                return null;
            }
        } catch (Exception e) {
            return null;
        }
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}

4、form_data传字段
public void fileUpload(String name) {
    try {
        String url = host + "/api";
        // 设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);
         // 创建表单数据
        MultiValueMap<String, String> formData = new LinkedMultiValueMap<>();
        formData.add("name", name);
        // 创建HTTP请求实体
        HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<>(formData, headers);
        // 发送POST请求
        ResponseEntity<String> response = restTemplate.exchange(
                url,
                HttpMethod.POST,
                requestEntity,
                String.class
        );
        System.out.println(response);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

Java实现根据HTTP接口调用工具类的基本思路如下: 1. 引入HTTP客户端库,例如Apache HttpClient或OkHttp。 2. 封装HTTP请求和响应的工具类,例如: ``` public class HttpUtils { // 发送HTTP GET请求 public static String get(String url) throws IOException { CloseableHttpClient httpClient = HttpClients.createDefault(); HttpGet httpGet = new HttpGet(url); CloseableHttpResponse response = httpClient.execute(httpGet); String result = EntityUtils.toString(response.getEntity()); response.close(); httpClient.close(); return result; } // 发送HTTP POST请求 public static String post(String url, Map<String, String> params) throws IOException { CloseableHttpClient httpClient = HttpClients.createDefault(); HttpPost httpPost = new HttpPost(url); List<NameValuePair> nameValuePairs = new ArrayList<>(); for (Map.Entry<String, String> entry : params.entrySet()) { nameValuePairs.add(new BasicNameValuePair(entry.getKey(), entry.getValue())); } httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8")); CloseableHttpResponse response = httpClient.execute(httpPost); String result = EntityUtils.toString(response.getEntity()); response.close(); httpClient.close(); return result; } } ``` 3. 在代码中使用HTTP工具类调用接口,例如: ``` // 发送HTTP GET请求 String result = HttpUtils.get("http://example.com/api?param1=value1&param2=value2"); // 发送HTTP POST请求 Map<String, String> params = new HashMap<>(); params.put("param1", "value1"); params.put("param2", "value2"); String result = HttpUtils.post("http://example.com/api", params); ``` 需要注意的是,Java实现根据HTTP接口调用工具类需要根据具体的业务逻辑和接口协议进行实现,需要进行接口参数的封装和解析,并进行异常处理和错误码处理。同时,还需要进行HTTP请求和响应的监控和管理,保证接口的稳定性和可靠性。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值