qq_41228873
Sea~Sky
采纳率71.4%
2019-07-10 16:41

java实现HTTP摘要认证

160
已采纳

图片说明

/**
     * 注册
     * @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条回答

  • qq_41228873 Sea~Sky 2年前
    @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;
            }
    
    点赞 评论 复制链接分享
  • caozhy 回答这么多问题就耍赖把我的积分一笔勾销了 2年前

为你推荐