使用Basic Auth和Java Servlet进行URL GET

时间:2016-06-06 20:01:43

标签: javascript java html servlets httpurlconnection

我有一个.jsp页面,它处理一些基本的html(文本字段,提交按钮表填充)和javascript。点击它会调用我的java Servlet类,它会分别处理请求和来自jsp的响应。我还有一个Java类来处理url连接以使用GET进行REST调用,这应该返回一个json字符串结果。这是场景:用户希望通过输入ID值来进行简单搜索,以使用REST填充表以连接到URL并获得json响应。

我已经单独测试了Java类,通过URL连接和基本身份验证进行REST调用,以获取json字符串中的数据,并且它完全正常。 (我已经编写了4种不同的方法来完成这项工作并且所有工作正常并返回预期的json)。

我已经单独测试了jsp页面,调用了servlet来填充" dummy"表中的值和servlet响应很好,表格按预期填充。

问题:

当我尝试使用从GET REST调用获得的值填充表时,它会挂起并且我没有得到任何结果。因此,我试图调查原因,并发现由于一些疯狂的原因,servlet不喜欢使用基本身份验证设置头的代码行来访问URL。我试着将基本的auth 1行代码注释掉(进行调试,所以现在我们没有认证)但是通过了一些" dummy"硬编码数据,它填充表格。

我实际上并不知道为什么servlet在设置身份验证时不喜欢它。我的猜测可能是它覆盖了servlet的响应路径,因此丢失了对jsp的初始响应位置? (即将json送回去的地方?)任何人都可以帮助我吗?有谁知道发生了什么?我对这个问题的假设是正确的吗?如果是这样,我该如何克服这个问题?

Javascript调用servlet:

$("#myForm2").submit(function(e) {
$.ajax({
       type: "GET",
       url: "servlet1", // the script where the form input is handled.
       data: $("#myForm2").serialize(), // serializes the form's elements.
       success: function(responseData){
            var dataObj = $.parseJSON(responseData)
            $('#myTable').append(>>add values to table here<<);
       });

e.preventDefault(); // avoid to execute the actual submit of the form.
$("#myForm2")[0].reset(); // clear previous values entered
});

Servlet类,jsp页面发出的请求和servlet的响应:

Rest getCallOnURL = new Rest(); // instance of my rest class

public void doGet(HttpServletRequest request, 
                  HttpServletResponse response) 
                  throws ServletException,IOException {
    // create a dummy string "test" to hold the ID value passed in from javascript
    String testID = request.getParameter("ID");

    // Hard coded - only for testing purposes
    if (testID.equals("1")){
        //call my java class' method to connect to url and retrieve the json string
        getCallOnURL.connectToUrlAndMakeAGetRequest();
        valueToPopulateTable = getCallOnURL.testJsonString;
    }

    response.setContentType(CONTENT_TYPE);
    PrintWriter out = response.getWriter();

    // using backslash to escape the quotes to make a valid json response
    out.print("{\"testRow\": \"valueToPopulateTable\"}");
    out.close();
}

用于进行URL调用和基本身份验证的My Java Class方法:

String testJsonString = "defaultValue";//testing purposes

//creates a valid encoded authentication string
private String basicAuth(String name, String pass){
    String authString = name + ":" + pass;
    byte[] authEncBytes = Base64.encodeBase64(authString.getBytes());
    String authStringEnc = new String(authEncBytes);
    return authStringEnc;    
}

private HttpURLConnection prepareGETConnection(final URL verifierURL)
throws IOException {                    
    final HttpURLConnection connection = (HttpURLConnection) verifierURL.openConnection();
    connection.setRequestMethod("GET");

    //this is the line which authorizes access to the url via Basic Auth
    connection.setRequestProperty("Authorization", "Basic " + basicAuth(name, password));

    return connection;
}

public void connectToUrlAndMakeAGetRequest(){
    try {
        String webPage = "URL HERE";// pass it a valid REST url with endpoints
        URL url = new URL(webPage);
        HttpURLConnection conn = prepareGETConnection(url);

        // get the url response json string
        InputStream getUrlresponse = conn.getInputStream(); 
        BufferedReader rd = new BufferedReader(new InputStreamReader(getUrlresponse));
        //get only the first line of the string - testing purposes only!
        testJsonString = rd.readLine();
        rd.close();
        conn.disconnect();

    } catch(IOException e){
        System.out.println("IO exception: "+e);
    }
} 

0 个答案:

没有答案