日期:2014-05-20  浏览次数:20692 次

http请求中传输的流要什么格式才能收到?
初学者,请多见谅。

我要用Post方式提交一些数据,这些数据要封装到流中,请问这个流要满足什么样的格式才能在servlet中的doPost方法中读取到。以下是java代码

InputStream is= request.getInputStream();
InputStreamReader isr = new InputStreamReader(is, "utf-8");
BufferedReader bf = new BufferedReader(isr);
// 可变字符串
StringBuffer sb = new StringBuffer();
// 存储一行数据(br.readLine每次读写一行)
String readLine=null;  
while((readLine=bf.readLine())!=null){  
sb.append(readLine).append("\n");  

System.out.println(sb.toString());

------解决方案--------------------
不用表单就用HttpURLConnection
Java code

//这里面两个参数
//url 服务器端servlet的访问地址
//aOutputData 字节数组 内容为key1=value1&key2=value2&key3=value3的形式 ,然后getBytes();
HttpURLConnection http=url.openConnection();
http.setConnectTimeout(5000);
        http.setReadTimeout(5000);
        http.setDoOutput(true);
        http.setDoInput(true);
        http.setAllowUserInteraction(false);
        http.setUseCaches(false);
        http.setRequestMethod("POST");
        http.setRequestProperty("Content-Type",
                "application/x-www-form-urlencoded");
        http.setRequestProperty("Content-Length", String
                .valueOf(aOutputData.length));
        http.setRequestProperty("Connection", "close");
        http
                .setRequestProperty(
                        "User-Agent",
                        "*** client");
        http.setRequestProperty("Accept", "text/xml");        
        http.connect();
        OutputStream out = http.getOutputStream();
        out.write(aOutputData);
        out.flush();