java关于post和get请求

本文详细介绍了HTTP和HTTPS协议下的GET和POST请求实现,包括HTTP的POST和GET方法,以及HTTPS的安全请求调用,展示了如何处理证书信任和连接验证。内容涵盖了Java编程中使用HttpURLConnection和HttpsURLConnection进行网络请求的方法。
摘要由CSDN通过智能技术生成

http请求和https请求是不一样的。
先看一下http请求的post与get

//post请求

public String callAPI(String nccip, JSONObject json) {
//		String nccip = ConfigUtils.getValueFromProperties("nccip");
		String param = json.toJSONString();
        StringBuffer sb = new StringBuffer("");
          try {
                  // 创建连接
                  URL url = new URL(nccip);
                  HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                  connection.setDoOutput(true);
                  connection.setDoInput(true);
                  connection.setRequestMethod("POST");
                  connection.setUseCaches(false);
                  connection.setInstanceFollowRedirects(true);
                  connection.setRequestProperty("Content-Type", "application/json;");
                  connection.setRequestProperty("encoding", "UTF-8");
                  connection.setConnectTimeout(120000);
                  connection.setReadTimeout(120000);
                  connection.connect();  
                  // POST请求
                  DataOutputStream out = new DataOutputStream(
                                  connection.getOutputStream());
                  out.write(param.getBytes("UTF-8"));
                  out.flush();
                  out.close();
                  // 读取响应
                  BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(),"utf-8"));
                  
                  String lines;
                  while ((lines = reader.readLine()) != null) {
                          lines = new String(lines.getBytes());
                          sb.append(lines);
                  }
                  reader.close();
                  // 断开连接
                  connection.disconnect();
          } catch (Exception e) {
              Logger.error(e.getMessage());
              ExceptionUtils.wrappBusinessException("调用接口("+ nccip +")发生异常:"+e.getMessage());
          } 
          return sb.toString();

get请求

 public JSONObject sendGet(String hsurl,JSONObject param ) throws Exception {
    	
        URL obj = new URL(url);
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();
        //默认值我GET
        con.setRequestMethod("GET");
        //添加请求头
        con.setRequestProperty("User-Agent", param);
        
        int responseCode = con.getResponseCode();
        System.out.println("\nSending 'GET' request to URL : " + url);
        System.out.println("Response Code : " + responseCode);

        BufferedReader in = new BufferedReader(
                new InputStreamReader(con.getInputStream()));
        String inputLine;
        StringBuffer response = new StringBuffer();

        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();

        //返回结果
        return response.toString();
}

其实这里网上有好多,不多赘述,可自行百度
https请求 的post请求 (设个适用于不同项目之间的接口调用 当时jdk版本不同是 jdk高的版本调用jdk版本低的接口)

public String uaphttp(String url, JSONObject obj) {
		UAPRSHttpClient uap = new UAPRSHttpClient();
		String str = "";
		try {
			str = uap.doPost(url, obj, ResourceContentType.JSON);
		} catch (UAPRSException e) {
		  ExceptionUtils.wrappBusinessException("调用接口("+ url +")发生异常:"+e.getMessage());
		}

		return str;
	}

public String doPost(String url, Object obj, ResourceContentType requestContentType) throws UAPRSException {
		UAPHttpResponse hr = null;
		if (requestContentType == ResourceContentType.JSON) {
			hr = this.doPostwithJson(url, obj);
		} else if (requestContentType == ResourceContentType.FORM) {
			hr = this.doPostWithForm(url, obj);
		}

		return hr != null ? hr.getContent() : "";
	}

https协议的get请求

 public JSONObject sendGet(String hsurl) throws Exception {
    	 URL url = null;
    	 //这是当时自己出的错误,url浏览器识别问题,当请求头有中文的时候 需要 +URLEncoder.encode("url","charset"); -- 具体格式如下
//String url11 = "https://dccusts.hisense.com/cmp-service/oapi/customer/customerInfo/page?pageIndex=1"+"&pageSize=1"+"&beginTime="+URLEncoder.encode("2021-12-1","utf-8")+"&endTime="+URLEncoder.encode("2021-12-1","utf-8");
    	 try {
    	        url = new URL(hsurl);
    	        HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
    	        X509TrustManager xtm = new X509TrustManager() {

					@Override
					public void checkClientTrusted(X509Certificate[] var1, String var2) throws CertificateException {
						// TODO Auto-generated method stub
					}

					@Override
					public void checkServerTrusted(X509Certificate[] var1, String var2) throws CertificateException {
						// TODO Auto-generated method stub
						
					}

					@Override
					public X509Certificate[] getAcceptedIssuers() {
						// TODO Auto-generated method stub
						return null;
					}
    	           
    	        };
    	 
    	        TrustManager[] tm = {xtm};
    	 
    	        SSLContext ctx = SSLContext.getInstance("TLS");
    	        ctx.init(null, tm, null);
    	 
    	        con.setSSLSocketFactory(ctx.getSocketFactory());
    	        con.setHostnameVerifier(new HostnameVerifier() {

					@Override
					public boolean verify(String var1, SSLSession var2) {
						// TODO Auto-generated method stub
						return true;
					}
    	        });
    	 
    	 
    	        InputStream inStream = (InputStream) con.getInputStream();
    	        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
    	        byte[] buffer = new byte[1024];
    	        int len = 0;
    	        while ((len = inStream.read(buffer)) != -1) {
    	            outStream.write(buffer, 0, len);
    	        }
    	        byte[] b = outStream.toByteArray();//网页的二进制数据
    	        outStream.close();
    	        inStream.close();
    	        String rtn = new String(b, "utf-8");
    	        if (StringUtils.isNotBlank(rtn)) {
    	            JSONObject object = JSONObject.parseObject(rtn);
    	            return object;
    	        }
    	    } catch (Exception e) {
    	        ExceptionUtils.wrappBusinessException("链接接口异常:" + e.getMessage());
    	    }
    	    return null;    	

    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

渴望知识de小白

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

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

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

打赏作者

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

抵扣说明:

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

余额充值