栏目分类:
子分类:
返回
文库吧用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
文库吧 > IT > 软件开发 > 后端开发 > Java

2022-- java发送http请求

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

2022-- java发送http请求

java发送http请求

会用到的包:

		
            commons-httpclient
            commons-httpclient
            3.1
        
一,表单方式

主请求:

 public static String getToken() throws Exception {
        NameValuePair[] data = {
                new NameValuePair("key", "value"),
                new NameValuePair("key", "value"),
                new NameValuePair("key", "value")};
        String access_token = HttpClient.sendByForm(
                "请求地址", data);
        System.out.println(access_token+"------getToken----------------");
        return access_token;
    }

工具类:

    public static String sendByForm(String url, NameValuePair[] data) throws Exception {
        try {
            PostMethod postMethod = null;
            postMethod = new PostMethod(url);
            postMethod.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
            //参数设置,需要注意的就是里边不能传NULL,要传空字符串
            postMethod.setRequestBody(data);
            //声明
            ProtocolSocketFactory fcty = new MySecureProtocolSocketFactory();
            //加入相关的https请求方式
            Protocol.registerProtocol("https", new Protocol("https", fcty, 443));

            org.apache.commons.httpclient.HttpClient httpClient = new org.apache.commons.httpclient.HttpClient();
            int response = httpClient.executeMethod(postMethod); // 执行POST方法
            RequestEntity requestEntity = postMethod.getRequestEntity();

            String result = postMethod.getResponseBodyAsString();

            JSONObject jsonObject1 = JSONObject.parseObject(result);
            String access_token = String.valueOf(jsonObject1.get("access_token"));
            System.out.println(access_token + "-----------access_token-------------");
            InputStream in = postMethod.getResponseBodyAsStream();
            //下面将stream转换为String
            StringBuffer sb = new StringBuffer();
            InputStreamReader isr = new InputStreamReader(in, "UTF-8");
            char[] b = new char[4096];
            for (int n; (n = isr.read(b)) != -1; ) {
                sb.append(new String(b, 0, n));
            }
            String returnStr = sb.toString();
            return access_token;
        } catch (Exception e) {
            System.out.println("请求异常" + e.getMessage() + e);
            e.printStackTrace();
            throw  e;
        }finally {
        }
    }
二,json方式

注意: 确认请求是否有ssl(http/https)
如果是http请求,用HttpURLConnection,忽略ssl代码可去掉
如果是https请求,用HttpsURLConnection,忽略ssl代码加上

  
    public static String httpsRequest2(String requestUrl, String requestMethod, Map map,String env) {
        try {
            // 创建SSLContext对象,并使用我们指定的信任管理器初始化
            TrustManager[] tm = {new MyX509TrustManager()};
            SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
            sslContext.init(null, tm, new java.security.SecureRandom());
            // 从上述SSLContext对象中得到SSLSocketFactory对象
            SSLSocketFactory ssf = sslContext.getSocketFactory();
            URL url = new URL(requestUrl);
            //如果是http请求,用HttpURLConnection
            HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
            conn.setSSLSocketFactory(ssf);
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setUseCaches(false);
            // 设置请求方式(GET/POST)
            conn.setRequestMethod(requestMethod);
            //接口需要token加入头
            //String Authorization="";
            //Authorization="Bearer " +HttpClient.getToken();
            conn.setRequestProperty("Authorization", Authorization);
            conn.setRequestProperty("Content-Type", "application/json;charset=utf-8");

            // 当outputStr不为null时向输出流写数据
            OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");

            //body参数在这里put到JSONObject中

            JSONObject parm = new JSONObject();
            for (String key : map.keySet()) {
                parm.put(key, map.get(key));
            }
            System.out.println(parm.toString() + "parm.toString()");
            writer.write(parm.toString());
            writer.flush();
            // 从输入流读取返回内容
            System.out.println(conn.getResponseCode());
            System.out.println(conn.getResponseMessage());
            InputStream inputStream = conn.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(
                    inputStream, "utf-8");
            BufferedReader bufferedReader = new BufferedReader(
                    inputStreamReader);
            String str = null;
            StringBuffer buffer = new StringBuffer();
            while ((str = bufferedReader.readLine()) != null) {
                buffer.append(str);
            }
            // 释放资源
            bufferedReader.close();
            inputStreamReader.close();
            inputStream.close();
            inputStream = null;
            conn.disconnect();
            return buffer.toString();
        } catch (ConnectException ce) {
            ce.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

跳过ssl验证工具类:

import javax.net.ssl.X509TrustManager;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;


public class MyX509TrustManager implements X509TrustManager {

    // 检查客户端证书
    public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
    }

    // 检查服务器端证书
    public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
    }

    // 返回受信任的X509证书数组
    public X509Certificate[] getAcceptedIssuers() {
        return null;
    }
}

转载请注明:文章转载自 www.wk8.com.cn
本文地址:https://www.wk8.com.cn/it/1040958.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 wk8.com.cn

ICP备案号:晋ICP备2021003244-6号