HTTP请求

1、get请求工具类

public static String requestGet(String url) throws Exception {
    String strResult = null;
    try {
        HttpClient httpsClient = HttpsClient.getInstance();
        HttpGet request = new HttpGet(url);
        HttpResponse response = httpsClient.execute(request);
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            strResult = EntityUtils.toString(response.getEntity());
            url = URLDecoder.decode(url, "UTF-8");
        } else {
            log.error("httpclientGet通信异常:{}" + url);
        }
    } catch (IOException e) {
        log.error("httpclientGet通信IO异常:{}:{}", url, ExceptionMessageHandler.toString(e));
        throw new Exception(e);
    } catch (NoSuchAlgorithmException e) {
        log.error("httpclientGet异常:{}:{}", url, ExceptionMessageHandler.toString(e));
        throw new Exception(e);
    } catch (KeyManagementException e) {
        throw new Exception(e);
    } catch (Exception e) {
        log.error("httpclientGet异常:{}:{}", url, ExceptionMessageHandler.toString(e));
        throw new Exception(e);
    }
    return strResult;
}
2、post请求方式,Content-type为application/json

public static String requestPost(String url, Map<String, Object> params) {

    CloseableHttpClient httpClient = HttpClients.createDefault();
    // 1 创建一个post对象
    HttpPost post = new HttpPost(url);
    post.addHeader("Content-type", "application/json; charset=utf-8");
    post.setHeader("Accept", "application/json");
    // 2 创建一个Entity。模拟一个xml
    StringEntity stringEntity = new StringEntity(params.toString(), "UTF-8");
    stringEntity.setContentEncoding("UTF-8");
    post.setEntity(stringEntity);
    // 3 执行post请求
    String responseResult = "";
    try {
        CloseableHttpResponse response = httpClient.execute(post);
         if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
        HttpEntity he = response.getEntity();
        String respContent = EntityUtils.toString(he, "UTF-8");
        responseResult = respContent;
        }
        response.close();
        httpClient.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return responseResult;
}
3、post请求方式,Content-type为application/x-www-form-urlencoded

public static String requestXPost(String url, String params, String accessToken) {

    CloseableHttpClient httpClient = HttpClients.createDefault();
    // 1 创建一个post对象
    HttpPost post = new HttpPost(url);
    //设置请求头,应用监控的请求头权限
    post.addHeader("Authoriz", accessToken);
    post.setHeader("Accept", "application/json, text/plain, */*");
    post.addHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8"); // 添加请求头
    // 2 创建一个Entity。模拟一个xml
    List<NameValuePair> nvps = new ArrayList<NameValuePair>();
    nvps.add(new BasicNameValuePair("businessId", params));
    UrlEncodedFormEntity urlEncodedFormEntity = null;
    try {
        urlEncodedFormEntity = new UrlEncodedFormEntity(nvps, "UTF-8");
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }
    post.setEntity(urlEncodedFormEntity);
    // 3 执行post请求
    String responseResult = "";
    try {
        CloseableHttpResponse response = httpClient.execute(post);
        HttpEntity he = response.getEntity();
        String respContent = EntityUtils.toString(he, "UTF-8");
        responseResult = respContent;
        response.close();
        httpClient.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return responseResult;
}


4 、HttpURLConnection 创建http 请求

public static String sendHttps(String xmlInfo) {
        //String a="";//请求参数
        String result = "";
        PrintWriter out = null;
        BufferedReader in = null;
        try {
            trustAllHosts();
            URL realUrl = new URL("https://apitest.bwjf.cn/openNozzle");
 
            //如果是https就是下面两行代码
            HttpsURLConnection conn = (HttpsURLConnection) realUrl.openConnection();
            conn.setHostnameVerifier(DO_NOT_VERIFY);
            //如果是http则是下面一行代码
            HttpURLConnection conn = (HttpURLConnection) realUrl.openConnection();
            // 设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            conn.setRequestProperty("Content-Type", "text/plain;charset=utf-8");
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
           
            // 获取URLConnection对象对应的输出流
            out = new PrintWriter(conn.getOutputStream());
            //加密
            String base64keyString = encoder(xmlInfo);
            // 发送请求参数
            out.print(base64keyString);
            System.out.println("发送报文:"+xmlInfo);
            System.out.println("加密报文:"+base64keyString);
            // flush输出流的缓冲
            out.flush();
           // System.out.println("响应报文:"+conn.getInputStream());
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream()));
           
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
            System.out.println("响应报文:"+result);
            String key = decoder(result);
            System.out.println("响应解密报文:"+key);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {// 使用finally块来关闭输出流、输入流
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return result;
    }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值