Sea~Sky 2019-07-10 16:41 采纳率: 71.4%
浏览 1748
已采纳

java实现HTTP摘要认证

图片说明

/**
     * 注册
     * @param url
     * @param param
     * @return
     * @throws NoSuchAlgorithmException 
     */
        @RequestMapping("insureResponsePost")
        @ResponseBody
        public  String insureResponsePost(String url, String param){
            PrintWriter out = null;
            InputStream is = null;
            BufferedReader br = null;
            String result = "";
            HttpURLConnection conn = null;
            StringBuffer strBuffer = new StringBuffer();
            CloseableHttpClient httpClient = HttpClients.createDefault(); 
            HttpPost httppost = new HttpPost(url);
            httppost.addHeader("Content-Type","application/json");
            httppost.setEntity(new StringEntity(param,"UTF-8"));
            try {

                URL realUrl = new URL(url);
                conn = (HttpURLConnection) realUrl.openConnection();

                // 设置通用的请求属性
                conn.setRequestMethod( "POST");
                conn.setConnectTimeout(20000);
                conn.setReadTimeout(300000);
                conn.setRequestProperty("Charset", "UTF-8");
                conn.setRequestProperty( "Content-Type", "application/json");
                conn.setRequestProperty( "Content-Encoding", "utf-8");
                // 发送POST请求必须设置如下两行
                conn.setDoOutput( true);
                conn.setDoInput( true);
                conn.setUseCaches( false);
                // 获取URLConnection对象对应的输出流
                out = new PrintWriter(conn.getOutputStream());
                // 发送请求参数
                out.print(param);
                // flush输出流的缓冲
                out.flush();
                System.out.println("=======================================================================");
                is = conn.getInputStream();
                br = new BufferedReader( new InputStreamReader(is));
                String line = null;
                while ((line=br.readLine())!= null) {
                    strBuffer.append(line);
                }
                result = strBuffer.toString();
            } catch (Exception e) {

                System. out.println( "发送 POST 请求出现异常!" + e);
                e.printStackTrace();
            }
            // 使用finally块来关闭输出流、输入流
            finally {
                try {
                    if (out != null) {
                        out.close();
                    }
                    if (br != null) {
                        br.close();
                    }
                    if (conn!= null) {
                        conn.disconnect();
                    }
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }
            return result;
        }

@RequestMapping("insureResponseBlockGet")
        @ResponseBody
        public String insureResponseBlockGet(String url,String username,String password,HttpUriRequest request){
            HttpServletResponse response1 = null;



            MessageDigest md5;
//          String authorization = request.getHeader("Authorization");
//          if (authorization != null) {
//              if (authorization.startsWith(DIGEST.trim())) {
//                  HashMap<String,String> authFields = splitAuthFields(authorization.substring(7));
//                  String newResponse = authFields = 
//              }
//          }
            System.out.println(username +"\n"+ password);
            HttpURLConnection hc = null;
            try {
                URI serverURI = request.getURI();
                Credentials creds = new UsernamePasswordCredentials(username,password);


                hc = (HttpURLConnection)new URL(url).openConnection();
                hc.setConnectTimeout(10000);
                hc.setReadTimeout(10000);
                hc.setDoInput(true);
                hc.setDoOutput(true);
                hc.setUseCaches(false);

                md5 = MessageDigest.getInstance("MD5");
                BASE64Encoder base = new BASE64Encoder();
                String ha1 = base.encode(md5.digest((username+password).getBytes("utf-8")));
                String ha2 = base.encode(md5.digest(url.getBytes("utf-8")));
                String response = base.encode(md5.digest((ha1+ha2).getBytes("utf-8")));
                System.out.println(response);

                StringBuilder sb = new StringBuilder();
                sb.append("Digest");
                sb.append("realm").append("=\"realm\",");
                sb.append("qop").append("=\"auth,auth-int\",");


            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            return "";
        }

以上代码只是第一次发送请求,返回401
现在不在明白第二次请求在Authorization字段给出信任书,包含认证信息
MD5加密,求大神赐教

  • 写回答

2条回答 默认 最新

  • Sea~Sky 2019-07-12 10:02
    关注
    @RequestMapping("httpSend")
            @ResponseBody
            public int httpSend(String url, String userName, String passWord, String jsonParam,String headValue) {
                CloseableHttpClient httpClient = null;
                int sc = 0;
                try {
                    URI serverURI = new URI(url);
    
                    CredentialsProvider credsProvider = new BasicCredentialsProvider();
                    credsProvider.setCredentials(new AuthScope(serverURI.getHost(), serverURI.getPort()),
                            new UsernamePasswordCredentials(userName, passWord));
                    httpClient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build();
    
                    HttpPost post = new HttpPost(url);
    
                    // 构造消息头
                    post.setHeader("Content-type", "application/viid+json; charset=utf-8");
                    if (headValue != null)
                        post.setHeader("User-Identify", headValue);
                    post.setEntity(new StringEntity(jsonParam, "UTF-8"));// 发送xml字符串数据
                    HttpResponse response = httpClient.execute(post);
                    String result = EntityUtils.toString(response.getEntity());
                    System.out.println("返回的消息:" + result);
                    System.out.println("返回的状态: " + response.getStatusLine().getStatusCode());
                    System.out.println("返回的类型: " + response.getEntity().getContentType());
                    sc = response.getStatusLine().getStatusCode();
                    EntityUtils.consume(response.getEntity());
    
                    httpClient.close();
    
    
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if (httpClient != null) {
                        try {
                            httpClient.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
                return sc;
            }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题