如何在Java中执行http post?
这是我正在使用的代码。它不是将数据发布到页面,而是像普通文本文件一样下载数据。因此,我实际上得到了返回的html代码,并且表单没有被提交 我知道html表单是有效的。如果我在浏览器中打开它,我可以发布到它,我的数据将显示在我的数据库中。我猜我遗漏了一个参数什么的如何在Java中执行http post?,java,http,post,Java,Http,Post,这是我正在使用的代码。它不是将数据发布到页面,而是像普通文本文件一样下载数据。因此,我实际上得到了返回的html代码,并且表单没有被提交 我知道html表单是有效的。如果我在浏览器中打开它,我可以发布到它,我的数据将显示在我的数据库中。我猜我遗漏了一个参数什么的 public void testComm () { try { URL url; URLConnection urlConn; DataOutputStream printout
public void testComm ()
{
try
{
URL url;
URLConnection urlConn;
DataOutputStream printout;
DataInputStream input;
url = new URL ("http://mysite.com/myform.html");
// URL connection channel.
urlConn = url.openConnection();
// Let the run-time system (RTS) know that we want input.
urlConn.setDoInput (true);
// Let the RTS know that we want to do output.
urlConn.setDoOutput (true);
// No caching, we want the real thing.
urlConn.setUseCaches (false);
// Specify the content type.
urlConn.setRequestProperty
("Content-Type", "application/x-www-form-urlencoded");
// Send POST output.
printout = new DataOutputStream (urlConn.getOutputStream ());
String content =
"txtLevelName=" + URLEncoder.encode ("level1") +
"&txtLevelData=" + URLEncoder.encode ("abcd");
printout.writeBytes (content);
printout.flush ();
printout.close ();
// Get response data.
input = new DataInputStream (urlConn.getInputStream ());
String str;
while (null != ((str = input.readLine())))
{
System.out.println (str);
}
input.close ();
}
catch (MalformedURLException me)
{
System.err.println("MalformedURLException: " + me);
}
catch (IOException ioe)
{
System.err.println("IOException: " + ioe.getMessage());
}
}
也许你做得不对。看起来您正在将其发布到表单中,而不是操作中。我正在做什么(我知道有一些框架用于此,但我希望它重量轻): postString与您的内容字符串相同
//编辑:噢,正如sid上面提到的:您的url是一个html页面???您已经发送了一个POST请求。将请求方法设置为POST的是
urlConn.setDoOutput(true)
。显然,您将请求发送到了错误的URL。在浏览器中打开HTML页面。右键单击并查看源。在HTML源代码中找到HTML
元素。它应该看起来像:
检查其操作
属性。这正是你必须发布到的URL
另见:
- 您可以尝试jsoup:
它非常容易使用:
Document doc = Jsoup.connect("http://example.com")
.data("query", "Java")
.post();
从URL加载文档:
你有没有理由避免这样的事情,让它为你完成大部分工作?我不知道你说的恢复HTML是什么意思;你是说当你从浏览器发布表单时,你没有返回HTML?你是将表单发布到表单还是操作???请打印您的html和操作脚本。
Document doc = Jsoup.connect("http://example.com")
.data("query", "Java")
.post();