2

我想将一些数据发送到我的测试页面,并接收由服务器执行的页面。我当前的结果 = 服务器没有返回任何内容。使用的 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);
           }
       }


 }
 }

有人可以帮忙吗?谢谢(抱歉英语不好,不是我的母语:))

编辑:解决了

4

1 回答 1

1

谢谢威廉,

更新答案供大家参考:

根据威廉的回答:

转变

urlConnection.setRequestProperty("内容长度", "" + queryString.length());

((HttpURLConnection) urlConnection).setFixedLengthStreamingMode(queryString.length());

这解决了这个问题。

于 2013-09-13T16:36:48.440 回答