我有以下代码来获取 URL 的内容..
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package javaapplication3;
/**
*
* @author Ravi
*/
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
public class Main {
/**
* @param args
*/
public static void main(String[] args) {
HttpURLConnection connection = null;
OutputStreamWriter wr = null;
BufferedReader rd = null;
StringBuilder sb = null;
String line = null;
URL serverAddress = null;
try {
serverAddress = new URL("http://192.16.110.11:8084/RaviTest/index.jsp?id=3");
//set up out communications stuff
connection = null;
//Set up the initial connection
connection = (HttpURLConnection)serverAddress.openConnection();
connection.setRequestMethod("GET");
connection.setDoOutput(true);
connection.setReadTimeout(10000);
connection.connect();
//get the output stream writer and write the output to the server
//not needed in this example
//wr = new OutputStreamWriter(connection.getOutputStream());
//wr.write("");
//wr.flush();
//read the result from the server
rd = new BufferedReader(new InputStreamReader(connection.getInputStream()));
sb = new StringBuilder();
while ((line = rd.readLine()) != null)
{
sb.append(line + '\n');
}
System.out.println(sb.toString());
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
finally
{
//close the connection, set all objects to null
connection.disconnect();
rd = null;
sb = null;
wr = null;
connection = null;
}
}
}
但是此代码仅复制指定 URL 的内容。
相反,如果我想连接到 jsp 页面,我可以获取该 JSP 页面动态发送的值吗...
例如,如果我有一个页面 http://192.16.110.51/WelcomeProject/index.jsp
我应该能够传递一个变量,然后index.jsp页面将向我传递回附加有hello world的变量,或者对变量进行一些操作并将结果发送回我。我怎样才能实现这一点?...如果不是 HttpURLConnection..是否还有其他方法可以完成此任务。
最佳答案
这是修改自的示例:http://www.java2s.com/Code/JavaAPI/java.net/URLConnectionsetDoOutputbooleandooutput.htm (我删除了响应部分,您可能实际上想要它)
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.net.URL;
import java.net.URLConnection;
public class MainClass {
public static void main(String args[]) throws Exception {
String query = "id=3";
URLConnection uc = new URL("http://192.16.110.11:8084/RaviTest/index.jsp").openConnection();
uc.setDoOutput(true);
uc.setAllowUserInteraction(false);
DataOutputStream dos = new DataOutputStream(uc.getOutputStream());
// The POST line, the Accept line, and
// the content-type headers are sent by the URLConnection.
// We just need to send the data
dos.writeBytes(query);
dos.close();
}
}
关于java - 如何使用 HttpURLConnection 传递变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5614074/