Java代码实现执行HTTP请求

1.导入依赖:

<dependency>
    <groupId>com.squareup.okhttp3</groupId>
    <artifactId>okhttp</artifactId>
    <version>3.14.0</version>
</dependency>

2.执行POST请求代码方式一:

/**
     * 执行POST请求
     * @param url 请求地址
     * @param json 请求参数
     * @param token 请求头参数
     */
    public void OkHttpPost(String url, String json,String token){

        //ssl认证重写
        OkHttpClient okHttpClient=new OkHttpClient.Builder().hostnameVerifier(
                new HostnameVerifier() {
                    @Override
                    public boolean verify(String s, SSLSession sslSession) {
                        return true;
                    }
                }
        ).build();
        RequestBody requestBody=new FormBody.Builder()
                .add("mobile","13256562332")
                .add("passwd","123456")
                .add("roleId","1")
                .add("type","Admin")
                .build();

        MediaType mediaType = MediaType.parse("application/json");

        Request request=new Request.Builder()
                .url(url)
                .post(RequestBody.create(mediaType, json))
//                .addHeader("token",token)
                .addHeader("content-type", "application/json")
                .addHeader("cache-control", "no-cache")
                .build();
        Call call=okHttpClient.newCall(request);

        try {
            Response response=call.execute();
            System.out.println(response.body().string());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        String json = "";
        String token = "8a89487e30419af40b6c9c406b75a80c_120";
       OkHttpPost("http://127.0.0.1:10086/api/driver/edit",json,token);
        
    }

3.执行POST请求方式二:

private Integer post(String url, MocInfo info, MocInfo.Action action) {

        OutputStream out = null;
        HttpURLConnection conn = null;
        int result = -10;
        String body = null;
        try {
            body = JSONObject.toJSONString(info);//把对象转换成JSON格式的字符串
            //url=127.0.0.1:8080/app/edit
            conn = (HttpURLConnection) new URL(url).openConnection();
            conn.setConnectTimeout(30 * 1000);
            conn.setReadTimeout(30 * 1000);
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Accept", "*/*");
            conn.setRequestProperty("Content-Type", "application/json");
            conn.setRequestProperty("Connection", "keep-alive");
            conn.setRequestProperty("Accept-Encoding", "gzip");
            conn.setRequestProperty("Accept-Charset", "utf-8");
            conn.connect();
            out = conn.getOutputStream();
            out.write(body.getBytes(StandardCharsets.UTF_8));
            out.flush();
            result = conn.getResponseCode();
        } catch (Exception e) {
            log.error("Post [" + url + "] Err :" + e.getMessage());
        } finally {
            if (conn != null) {
                conn.disconnect();
            }
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    log.error(e.getMessage(), e);
                }
            }
        }
        if (result < 200 || result >= 300) {
            log.info("Post .. " + url + " : " + body);
        }
        return result;
    }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

iamlzjoco

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值