我想将一些数据发送到我的测试页面,并接收服务器执行的页面。 我当前的结果=服务器什么也没有返回。 使用的HTML表单:
<form action = "s.php" method = "post">
<input type = "text" name = "test" />
<input type = "submit" />
</form>
S.php - 应处理前面提到的数据的脚本:
<? echo $_POST["test"] ?>
所以我想收到值为“test”文本字段的源代码。 用于此的Java代码:
package nettests;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.OutputStreamWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
class NetTests
{
public static void main(String args[]) throws IOException {
URL targetURL = new URL("http://lerain.tode.cz/s.php");
HttpURLConnection conn = (HttpURLConnection)targetURL.openConnection();
//data send via POST request
String data = "test=someData";
conn.setDoOutput(true);
conn.setInstanceFollowRedirects(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("charset", "UTF-8");
conn.setRequestProperty("Content-Length", Integer.toString(
data.length()));
conn.setUseCaches(false);
try(OutputStreamWriter out = new OutputStreamWriter(
conn.getOutputStream()))
{
out.write(data);
}
//reading code after POST request (here I want to have value from "test" field
try(BufferedReader in = new BufferedReader(new InputStreamReader(
conn.getInputStream())))
{
String currentLine;
while((currentLine = in.readLine()) != null)
{
System.out.println(currentLine);
}
}
}
}
有人可以帮忙吗? 谢谢 (抱歉英语不好,不是我的母语:))
编辑:已解决
答案 0 :(得分:1)
谢谢William,
更新每个人的参考答案:
根据威廉的回答:
切换
urlConnection.setRequestProperty(“Content-Length”,“”+ queryString.length());
到
((HttpURLConnection类) 的URLConnection).setFixedLengthStreamingMode(queryString.length());
解决了这个问题。