当前位置: 首页 > news >正文

公司网站制作的教程怎么搭建自己的网站

公司网站制作的教程,怎么搭建自己的网站,B2B网站建设商务排名,大型o2o网站开发时间公司有个需求是发起https请求对接国家数据接口,需要带header、cookie,并关闭ssl证书验证,搜了很多文章,都说用HttpsURLConnection发起请求,但不知为啥在封装body参数的时候一直报400封装出错,也欢迎指出不足…

公司有个需求是发起https请求对接国家数据接口,需要带header、cookie,并关闭ssl证书验证,搜了很多文章,都说用HttpsURLConnection发起请求,但不知为啥在封装body参数的时候一直报400封装出错,也欢迎指出不足。遂找了这古代的方法,方法虽老但能解决实际问题且不用导包。

HttpsURLConnection报错方法示例:

			// 发起HTTPS POST请求URL url = new URL("https://example.com/api/resource");connection = (HttpsURLConnection) url.openConnection();// 设置请求方法为POSTconnection.setRequestMethod("POST");connection.setDoOutput(true); // 允许写入请求体connection.setRequestProperty("Content-Type", "application/json");// 封装请求体参数,这里假设参数是一个 JSON 对象String requestBody = "{\"param1\":\"value1\", \"param2\":\"value2\"}";//此处封装body参数一直报错try (OutputStream os = connection.getOutputStream()) {byte[] input = requestBody.getBytes("utf-8");os.write(input, 0, input.length);}// 获取响应int responseCode = connection.getResponseCode();System.out.println("Response Code: " + responseCode);BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));String line;StringBuilder response = new StringBuilder();while ((line = reader.readLine()) != null) {response.append(line);}reader.close();System.out.println("Response: " + response.toString());

使用方法(其实cookie也是在header里面):

1.创建默认证书(可选)

    /*** 创建默认证书** @return*/public static CloseableHttpClient createSSLClientDefault() {try {SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {// 信任所有public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {return true;}}).build();HostnameVerifier hostnameVerifier = NoopHostnameVerifier.INSTANCE;SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, hostnameVerifier);return HttpClients.custom().setSSLSocketFactory(sslsf).build();} catch (Exception e) {e.printStackTrace();}return HttpClients.createDefault();}

2.post请求:

   public static String dopost(String reqUrl, String json, Map<String, String> headerMap) {String strResult = "";CloseableHttpResponse response = null;CloseableHttpClient httpClient = null;if (reqUrl.startsWith("https")) {//可选httpClient = createSSLClientDefault();} else {httpClient = HttpClients.custom().setDefaultRequestConfig(RequestConfig.custom().setSocketTimeout(1 * 60 * 1000).setConnectTimeout(1000).setConnectionRequestTimeout(1000).build()).build();}HttpEntity httpEntity = null;try {HttpPost httpPost = new HttpPost(reqUrl);if (headerMap != null) {headerMap.forEach((k, v) -> httpPost.addHeader(k, v));}StringEntity entity = new StringEntity(json, "UTF-8");//解决中文乱码问题entity.setContentType("application/json");httpPost.setEntity(entity);response = httpClient.execute(httpPost, HttpClientContext.create());int status = response.getStatusLine().getStatusCode();httpEntity = response.getEntity();if (status == 200) {String string = EntityUtils.toString(httpEntity, StandardCharsets.UTF_8);return EntityUtils.toString(httpEntity, StandardCharsets.UTF_8);} else {log.error(reqUrl + " 请求错误:\r\t" + EntityUtils.toString(httpEntity, StandardCharsets.UTF_8));}return strResult;} catch (IOException e) {e.printStackTrace();} finally {try {if (httpEntity != null) {EntityUtils.consume(httpEntity);}if (response != null) {response.close();}} catch (IOException e) {e.printStackTrace();}}return strResult;}

3.get请求:

    public static ResultVo sendHttpsRequest(String url, String requestMethod, Stringparam, Map<String, String> headers, String cookieStr) {ResultVo vo = new ResultVo();StringBuilder result = new StringBuilder();try {//屏蔽证书验证SSLContext sc = SSLContext.getInstance("SSL");sc.init(null, new TrustManager[]{new X509TrustManager() {@Overridepublic void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {}@Overridepublic void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {}@Overridepublic X509Certificate[] getAcceptedIssuers() {return new X509Certificate[0];}}}, new SecureRandom());URL console = new URL(url);HttpsURLConnection conn = (HttpsURLConnection) console.openConnection();// GET/POSTconn.setRequestMethod(requestMethod);
//            conn.setDoOutput(true);conn.setDoInput(true);if ("POST".equals(requestMethod)) {try (DataOutputStream wr = new DataOutputStream(conn.getOutputStream())) {wr.writeBytes(param);wr.flush();}conn.setRequestProperty("Content-Type", "application/json");} else {if (null != param) {OutputStream outputStream = conn.getOutputStream();// 注意编码格式outputStream.write(param.getBytes("UTF-8"));outputStream.close();}}if (ObjectUtil.isNotEmpty(headers)) {for (String s : headers.keySet()) {conn.setRequestProperty(s, headers.get(s));}}conn.setRequestProperty("Cookie", cookieStr);// 设置证书忽略相关操作conn.setSSLSocketFactory(sc.getSocketFactory());conn.setHostnameVerifier(new HostnameVerifier() {@Overridepublic boolean verify(String s, SSLSession sslSession) {return true;}});conn.connect();int responseCode = conn.getResponseCode();if (responseCode == HttpURLConnection.HTTP_OK) {InputStream is = conn.getInputStream();BufferedReader br = new BufferedReader(new InputStreamReader(is));String ret = "";//输出响应信息while ((ret = br.readLine()) != null) {if (ret != null && !ret.trim().equals("")) {result.append(new String(ret.getBytes("utf-8"), "utf-8"));}}List<String> cookies = conn.getHeaderFields().get("Set-Cookie");//这里返回了连接的cookie信息if (cookies != null) {for (String cookie : cookies) {if (cookie.contains(SyncInfoConfig.COOKIE_NAME)) {// 找到目标CookieString sidCookie = cookie.split(";\\s*")[0];vo.setCookieInfo(sidCookie);break;}}}conn.disconnect();br.close();}} catch (NoSuchAlgorithmException | KeyManagementException | MalformedURLException e) {e.printStackTrace();} catch (IOException ioException) {ioException.printStackTrace();}if (ObjectUtil.isNotEmpty(result)) {vo.setResultStr(result.toString());}return vo;}
http://www.dinnco.com/news/54885.html

相关文章:

  • 哪个网站做婚礼邀请函好佛山网络公司 乐云seo
  • 做设计在哪个网站上找高清图片大全网络推广文案怎么写
  • 专门做毕业设计的网站如何做一个自己的电商平台
  • 所以免费爱做网站推广普通话的文字内容
  • 廊坊网站制作推广郑州好的seo外包公司
  • 高端品牌网站建设(杭州)正规考证培训机构
  • 服务器可以做网站seo查询系统源码
  • 怎样找回网站备案密码错误百度做网站需要多少钱
  • 网站做系统叫什么软件有哪些广州网站推广排名
  • 中国建设工程造价管理协会seo优化排名
  • 洛阳哪里做网站网站流量数据
  • 洞口做网站的公司推荐希爱力跟万艾可哪个猛
  • 免费的短视频app有哪些云seo
  • 电子商务平台经营者制定平台服务协议和交易规则时关键词整站优化
  • 网站优化是外包还是自己做网店推广的作用是
  • 不会编程 做网站前端性能优化
  • 做网站电商山西太原百度公司
  • 在线免费logo设计网站semikron
  • 做计划的网站网站收录查询入口
  • 滕建建设集团网站网络营销与策划
  • 建筑铝模板多少钱一平方米seo搜索铺文章
  • 珠海网站制作推广邀请注册推广赚钱
  • 搭建电商分销系统天津seo博客
  • 杭州网站现场备案如何做推广呢
  • 订单查询网站怎么做头条新闻 最新消息条
  • 安徽观元建设有限公司网站徐州百度快照优化
  • edu域名网站百度推广一年收费标准
  • 网站建设填空题培训方案怎么做
  • 动漫制作专业学什么关键词诊断优化全部关键词
  • 网站建设千套素材海南seo代理加盟供应商