302尝试使用jsp获取url的内容时发现错误

时间:2011-06-29 18:55:32

标签: java jsp jquery

我试图通过在jsp中编写一些代理代码,从我的计算机本地对其他域进行ajax调用。这是我调用proxy.jsp页面的jQuery AJAX代码。

    var search_agile_metadata = 'https://search.xyz.com/rest-services/services/ag/get?id=';

var on_show_info = function() {
var outOfDomainCall = search_agile_metadata + current_doc_info.id;//An XML document

                request_meta_info = $.ajax({
                url: "proxy.jsp?url=" + outOfDomainCall ,
                type: 'GET',
                success: on_get_metadata,
                error: on_get_metadata_agile

        });
    };

var on_get_metadata = function(data, text_status, XMLHttpRequest) {
        console.log(data);
}

我的proxy.jsp文件是: -

    <%@ page language="java" import="org.w3c.dom.*,javax.xml.parsers.DocumentBuilder,javax.xml.parsers.DocumentBuilderFactory,java.net.*,java.io.*" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%
final String login ="user";
final String password ="pass";

Authenticator.setDefault(new Authenticator() {
    protected PasswordAuthentication getPasswordAuthentication() {
        return new PasswordAuthentication (login, password.toCharArray());
    }
});

String a_Url = request.getParameter( "url" ) ;
String l_Content = "" ;

if( a_Url!=null && a_Url.length()>0 )
l_Content = GetContent( a_Url ).toString() ;
out.println( l_Content );
%>
<%!
StringBuffer GetContent( String a_Url ) throws Exception
{
URL l_URL = new URL(a_Url);
BufferedReader l_Reader = new BufferedReader( new InputStreamReader( l_URL.openStream()));

StringBuffer l_Result = new StringBuffer("") ;
String l_InputLine = null ;
while ((l_InputLine = l_Reader.readLine()) != null)
//System.out.println("Print3" +l_InputLine );
l_Result.append( l_InputLine );

l_Reader.close();
return( l_Result ) ;
}
%>

当我从这个proxy.jsp文件中得到响应时,我收到此错误: -

<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN"><html><head><title>302 Found</title></head><body><h1>Found</h1><p>The document has moved <a href="HTTP://search.xyz.com/rest-services/se/agile/get?id=CD90">here</a>.</p></body></html>

如果我检查上面的jQuery AJAX代码中的状态代码那么它是200.这意味着在proxy.jsp页面中发生了一些事情。为什么它无法获取url的内容。任何建议将不胜感激......

1 个答案:

答案 0 :(得分:1)

状态代码302表示您尝试从中提取信息的文件已移动。 302是临时重定向,您可以在此处查看定义:HTTP status code definitions

您的ajax调用很好,但您的JSP代码不遵循302重定向。我不确定它是否能解决这个问题,但是在JSP中使用apache的HttpClient代码是值得的。

希望这有帮助。

我用HttpClient完成的代码片段

httpclient.getParams().setParameter(AuthPNames.PROXY_AUTH_PREF, AuthPolicy.BASIC);      
Credentials creds = new UsernamePasswordCredentials(proxyUsername, proxyPassword);

CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(AuthScope.ANY, creds);
httpclient.getCredentialsProvider().setCredentials(AuthScope.ANY, credsProvider.getCredentials(AuthScope.ANY));