java http请求接口

    private static final String DEFAULT_CHARSET = "UTF-8";


/**
     * 执行HTTP POST请求
     * @param url url
     * @param param 参数
     * @return
     */
    public static String httpPostWithJSON(String url, JSONObject param) {
        CloseableHttpClient client = null;
        try {
            if(url == null || url.trim().length() == 0){
                throw new Exception("URL is null");
            }
            HttpPost httpPost = new HttpPost(url);
            client = HttpClients.createDefault();
            if(param != null){
                StringEntity entity = new StringEntity(param.toString(),"utf-8");//解决中文乱码问题
                entity.setContentEncoding(DEFAULT_CHARSET);
                entity.setContentType("application/json");
//                entity.setContentType("text/xml");
                httpPost.setEntity(entity);
            }
            HttpResponse resp = client.execute(httpPost);
            if(resp.getStatusLine().getStatusCode() == 200) {
                return EntityUtils.toString(resp.getEntity(), DEFAULT_CHARSET);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            close(client);
        }
        return null;
    }

    /**
     * 执行HTTP GET请求
     * @param url url
     * @param param 参数
     * @return
     */
    public static String httpGetWithJSON(String url, Map<String, ?> param) {
        CloseableHttpClient client = null;
        try {
            if(url == null || url.trim().length() == 0){
                throw new Exception("URL is null");
            }
            client = HttpClients.createDefault();
            if(param != null){
                StringBuffer sb = new StringBuffer("?");
                for (String key : param.keySet()){
                    sb.append(key).append("=").append(param.get(key)).append("&");
                }
                url = url.concat(sb.toString());
                url = url.substring(0, url.length()-1);
            }
            HttpGet httpGet = new HttpGet(url);
            HttpResponse resp = client.execute(httpGet);
            if(resp.getStatusLine().getStatusCode() == 200) {
                return EntityUtils.toString(resp.getEntity(), DEFAULT_CHARSET);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            close(client);
        }
        return null;
    }

    /**
     * 关闭HTTP请求
     * @param client
     */
    private static void close(CloseableHttpClient client){
        if(client == null){
            return;
        }
        try {
            client.close();
        } catch (Exception e) {
        }
    }





使用时引入:

        
        JSONObject param = new JSONObject();
        param.put("paperNo", paperNo);	// 身份证号
        System.out.println("**************接口入参:"+param.toString());
        String result = httpPostWithJSON("http://*****", param);


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java中可以使用HttpURLConnection或者Apache HttpClient来发送HTTP请求。其中,HttpURLConnection是Java标准库中提供的类,它可以通过向服务器发送不同的HTTP请求方法(如GET、POST等)来实现与服务器的交互。Apache HttpClient是一个第三方库,相对于HttpURLConnection来说,它提供了更多的功能和更简洁的API接口。 下面以HttpURLConnection为例介绍如何发送POST请求: ```java import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.nio.charset.StandardCharsets; public class HttpPostExample { public static void main(String[] args) throws IOException { String url = "http://example.com/api/v1/user"; // 请求的url地址 String body = "{\"username\":\"test\",\"password\":\"123456\"}"; // 请求体 URL obj = new URL(url); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); con.setRequestMethod("POST"); // 设置请求方法为POST con.setRequestProperty("Content-Type", "application/json; charset=UTF-8"); // 设置请求头 con.setDoOutput(true); // 允许输出流 // 发送请求体 try (DataOutputStream wr = new DataOutputStream(con.getOutputStream())) { byte[] bodyBytes = body.getBytes(StandardCharsets.UTF_8); wr.write(bodyBytes); wr.flush(); } // 处理响应结果 int responseCode = con.getResponseCode(); System.out.println("Response Code : " + responseCode); try (BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()))) { String inputLine; StringBuilder response = new StringBuilder(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } System.out.println("Response Body : " + response.toString()); } } } ``` 以上代码演示了如何使用HttpURLConnection发送POST请求,其中`url`表示请求的url地址,`body`表示请求体,需要根据实际情况进行修改。在发送请求时,需要设置请求方法为POST,并设置请求头`Content-Type`为`application/json; charset=UTF-8`。在发送请求体后,可以通过`getResponseCode`方法获取响应状态码,通过`getInputStream`方法获取响应内容。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值