jsp如何调用其他的url并且获得其数据

描述:不是获得当前url路径,是调用其他的url

目前为止还不知道LZ到底要的是什么,不管了,再来个Ajax的,很简单的demo。

把两个jsp放到Web应用里面,要放在同一个目录下,打开ajaxGetPost.jsp这个页面,ajaxGetPost.jsp页面通过Ajax访问ajaxGetPostUse.jsp页面。

[code="jsp"]<%@ page language="java" pageEncoding="GBK"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">


Ajax Using Get and Post
<br> var xmlHttp;<br> // 创建对象<br> function createXmlHttpRequest()<br> {<br> if(window.XMLHttpRequest)<br> {<br> xmlHttp = new XMLHttpRequest();<br> } else if(window.ActiveXObject)<br> {<br> xmlHttp = new ActiveXObject(&quot;Microsoft.XMLHttp&quot;);<br> } else {<br> alert(&quot;Your Browser Don&#39;t Support AJAX!&quot;);<br> return false;<br> }<br> return true;<br> }<br> // 拼装查询字符串<br> function createQueryString()<br> {<br> var firstName = document.getElementById(&quot;firstName&quot;).value;<br> var birthday = document.getElementById(&quot;birthday&quot;).value;<br> var queryString = &quot;firstName=&quot; + firstName + &quot;&amp;birthday=&quot; + birthday;<br> //两次编码解决中文乱码问题<br> return encodeURI(encodeURI(queryString));<br> }<br> // GET方式进行异步请求<br> function doRequestUsingGet()<br> {<br> if(!createXmlHttpRequest()) {<br> return;<br> }</p> <pre><code> var url = &quot;ajaxGetPostUse.jsp?&quot; + createQueryString(); //IE会自动缓存异步通信结果,在url后加一个毫秒数,使每次请求的地址都不一样,可解决问题 url = url + &quot;&amp;timestamp=&quot; + new Date().getTime(); xmlHttp.onreadystatechange = handleStateChange; xmlHttp.open(&quot;GET&quot;, url); xmlHttp.send(null); } // POST方式进行异步请求 function doRequestUsingPost() { if(!createXmlHttpRequest()) { return; } //IE会自动缓存异步通信结果,在url后加一个毫秒数,使每次请求的地址都不一样,可解决问题 var url = &quot;ajaxUsingGetPost?timestamp=&quot; + new Date().getTime(); var queryString = createQueryString(); xmlHttp.onreadystatechange = handleStateChange; xmlHttp.open(&quot;POST&quot;, url); xmlHttp.setRequestHeader(&quot;Content-Type&quot;, &quot;application/x-www-form-urlencoded&quot;); xmlHttp.send(queryString); } // 处理服务端返回数据 function handleStateChange() { if(xmlHttp.readyState == 4 &amp;&amp; xmlHttp.status == 200) { var responseDiv = document.getElementById(&quot;serverResponse&quot;); // responseDiv.innerHTML = xmlHttp.responseText; // 原始 responseDiv.innerHTML = decodeURI(xmlHttp.responseText); // 解码 } } &lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;h4&gt; 哈哈,我的第一个Ajax程序O(∩_∩)O &lt;/h4&gt; &lt;h3&gt; 输入姓名和生日 &lt;/h3&gt; &lt;form&gt; &lt;input type=&quot;text&quot; id=&quot;firstName&quot; /&gt; &lt;br /&gt; &lt;input type=&quot;text&quot; id=&quot;birthday&quot; /&gt; &lt;br /&gt; &lt;input type=&quot;button&quot; value=&quot;Get&quot; onclick=&quot;doRequestUsingGet();&quot; /&gt; &lt;br /&gt; &lt;input type=&quot;button&quot; value=&quot;Post&quot; onclick=&quot;doRequestUsingPost();&quot; /&gt; &lt;/form&gt; &lt;div id=&quot;serverResponse&quot;&gt;&lt;/div&gt; &lt;/body&gt; </code></pre> <p></html>[/code]</p> <p>[code=&quot;jsp&quot;]&lt;%@ page language=&quot;java&quot; pageEncoding=&quot;GBK&quot;%&gt;<br> &lt;!DOCTYPE HTML PUBLIC &quot;-//W3C//DTD HTML 4.01 Transitional//EN&quot;&gt;<br> <html><br> <head><br> <title>Ajax Using Get and Post Use</title><br> </head><br> <body><br> &lt;%<br> String firstName = request.getParameter(&quot;firstName&quot;);<br> String birthday = request.getParameter(&quot;birthday&quot;);<br> // 返回给Ajax调用者的内容<br> out.println(&quot;Hello, &quot; + firstName + &quot;, your birthday is &quot; + birthday + &quot;.&quot;);<br> %&gt;<br> </body><br> </html>[/code]</p>

简单的通过URLConnection:
[code="java"]import java.net.*;
import java.io.*;
import java.util.Date;

public class URLConnectionDemo {

public static void main(String[] args) throws IOException {
    URL url = new URL("http://127.0.0.1:8080/cfStruts2Ex2/");
    URLConnection urlConn = url.openConnection();

    System.out.println("Date: " + new Date(urlConn.getDate()));
    System.out.println("Content-Type: " + urlConn.getContentType());

    int length = urlConn.getContentLength();
    System.out.println("Content-Lentgth: " + length);

    if (length > 0) {
        System.out.println("========== Content ==========");
        InputStream input = urlConn.getInputStream();

        int i = length;
        int c;
        while ((c = input.read()) != -1 && --i > 0) {
            System.out.print((char) c);
        }
        input.close();
    } else {
        System.out.println("No Content.");
    }
}

}[/code]

或者可以用HttpClient:
[code="java"]import java.io.IOException;

import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;

public class HttpClientTutorial {

private static String url = "http://www.baidu.com/";

public static void main(String[] args) {
    // Create an instance of HttpClient.
    HttpClient client = new HttpClient();

    // Create a method instance.
    GetMethod method = new GetMethod(url);

    // Provide custom retry handler is necessary
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(3, false));

    try {
        // Execute the method.
        int statusCode = client.executeMethod(method);

        if (statusCode != HttpStatus.SC_OK) {
            System.err.println("Method failed: " + method.getStatusLine());
        }

        // Read the response body.
        byte[] responseBody = method.getResponseBody();

        // Deal with the response.
        // Use caution: ensure correct character encoding and is not binary
        // data
        System.out.println(new String(responseBody, "GBK"));

    } catch (HttpException e) {
        System.err.println("Fatal protocol violation: " + e.getMessage());
        e.printStackTrace();
    } catch (IOException e) {
        System.err.println("Fatal transport error: " + e.getMessage());
        e.printStackTrace();
    } finally {
        // Release the connection.
        method.releaseConnection();
    }
}

}[/code]

如果需要鉴权,那就只能用HttpClient,而且要加鉴权:
[code="java"]String newUrl = "http://10.167.129.108/fnst_travel/BasicInformation.do";

NameValuePair[] paramPairs = new NameValuePair[] {
new NameValuePair("registrationPersonNum", "1"),
new NameValuePair("myName", "Chen Feng"),
new NameValuePair("myNameIDnumber", "123321123321"),
new NameValuePair("myNamePhonenumber", "15951836132") };

PostMethod method = new PostMethod(newUrl);
method.setRequestBody(paramPairs);

int statusCode = client.executeMethod(method);[/code]

你可以使用ajax得到返回的内容,然后再解析得到的内容就可以了

这个不是只要在第一个JSP页面ONload的时候用AJAX发起一个请求就可以了吗?

描述:不是获得当前url路径,是调用其他的url

1、如使用URLConnection 或 httpclient等工具抓取数据