http://blog.csdn.net/bfxyly/archive/2011/06/23/6563731.aspx
这里面的程序我照着模仿了一遍,按照这个流程能正常提交,但是,
in = new BufferedReader(new InputStreamReader(conn.getInputStream())); 这句话我始终没看懂,这是是要提交内容,和获得响应应该没什么关系吧,可是少了他就是不能正常提交,郁闷当中,有达人路过帮看下
这里面的程序我照着模仿了一遍,按照这个流程能正常提交,但是,
in = new BufferedReader(new InputStreamReader(conn.getInputStream())); 这句话我始终没看懂,这是是要提交内容,和获得响应应该没什么关系吧,可是少了他就是不能正常提交,郁闷当中,有达人路过帮看下
conn.getOutputStream():这个才是向服务器发送数据
调用这句代码时,会隐含的发送out数据出去,除非你显式的调用out.flush()以及设置doINput为false,否则都是在取input的时候,真正的请求才会发送出去的。
不调用这句代码,实际上请求数据还未发送出去,没发送出去,怎么提交呢?
貌似说到点子上了,那个显示调用out.flush()这句的意思,是不是直接写个out.flush()代码就行了?import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;public class URLTest {
public static void main(String[] args) {
String addressLogin = "http://127.0.0.1:8080/classSystem/doRegister";
PrintWriter out = null;
BufferedReader in = null;
try {
URL urlLogin = new URL(addressLogin);
URLConnection conn = urlLogin.openConnection();
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)"); conn.setDoOutput(true);
conn.setDoInput(true);
out = new PrintWriter(conn.getOutputStream());
out.write("name=bfdx&password=abcdead&email=hi&realName=abd");
out.flush();// in = new BufferedReader(
// new InputStreamReader(conn.getInputStream()));
// String line;
// while ((line = in.readLine()) != null) {
// System.out.println(line);
// } } catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (out != null) {
out.close();
}
if (in != null) {
in.close();
}
} catch (IOException e) { e.printStackTrace();
}
}
}
}这样子,把代码conn.setDoInput(true);改成conn.setDoInput(false);还是不行
http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4192018
You can not call getOutputStream alone and expect the flush method would cause
the request to be sent to the server. The only way to send out the request is by
calling getInputStream.
还可以参考:
http://www.360doc.com/content/10/1126/09/4154133_72516601.shtml
http://stackoverflow.com/questions/4844535/why-do-you-have-to-call-urlconnectiongetinputstream-to-be-able-to-write-out-to-u
(1)
引用:import sun.net.www.protocol.http.HttpURLConnection;
而不是:import java.net.HttpURLConnection;
(2)
HttpURLConnection conn =(HttpURLConnection)urlLogin.openConnection();
(3)
conn.setFixedLengthStreamingMode(param.length());参考:http://blog.sina.com.cn/s/blog_3fe375b70100notm.html