- HttpURLConnection.connect函数,实际上只是建立了一个与服务器的tcp连接,并没有实际发送http请求。
- 无论是post还是get,http请求实际上直到HttpURLConnection.getInputStream()这个函数里面才正式发送出去。
- 在readContentFromPost() 中,顺序是重中之重,对connection对象的一切配置(那一堆set函数)都必须要在connect()函数执行之前完成。而对 outputStream的写操作,又必须要在inputStream的读操作之前。这些顺序实际上是由http请求的格式决定的。
- http 请求实际上由两部分组成,一个是http头,所有关于此次http请求的配置都在http头里面定义,一个是正文content,在connect()函数里面,会根据HttpURLConnection对象的配置值生成http头,因此在调用connect函数之前,就必须把所有的配置准备好。
- 紧接着http头的是http请求的正文,正文的内容通过outputStream写入,实际上outputStream不是一个网络流,充其量是个字符串流,往里面写入的东西不会立即发送到网络,而是在流关闭后,根据输入的内容生成http正文。
- 至此,http请求的东西已经准备就绪~~。
- 在getInputStream()函数调用的时候,就会把准备好的http请求正式发送到服务器了,然后返回一个输入流,用于读取服务器对于此次http请求的返回信息。
- 由于http请求在getInputStream的时候已经发送出去了(包括http头和正文),因此在getInputStream()函数之后对connection对象进行设置(对http头的信息进行修改)或者写入 outputStream(对正文进行修改)都是没有意义的了,执行这些操作会导致异常的发生。
public class testhttp {
private String str_url="http://localhost:8080/new_web/httpmesg.jsp";
private String str_geturl="http://www.baidu.com/s?wd=e&rsv_bp=0&ch=&tn=baidu&bar=&rsv_spt=3&ie=utf-8&rsv_sug3=1&rsv_sug4=537&rsv_sug1=1&f=3&rsp=0&inputT=1471";
private String str_baidu="http://www.baidu.com?wd=e&test=1234ada";
private URL url;
private HttpURLConnection urlconn;
private URL get_url;
public void http(){
try {
url = new URL(str_url);
urlconn= (HttpURLConnection)url.openConnection();
urlconn.connect();
urlconn.setDoOutput(true);
urlconn.setDoInput(true);
urlconn.setUseCaches(false);
urlconn.setRequestMethod("POST");
urlconn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
//通过post方法发送的内容
String content="11req_http";
//向服务器端发送数据的输出流
OutputStream os=urlconn.getOutputStream();
BufferedWriter bw=new BufferedWriter(new OutputStreamWriter(os,"ascii"));
bw.write(content);
bw.flush();
//关闭后将输出流写入到http的content中
bw.close();
//发送请求信息,获得服务器返回数据的输入流
InputStream is=urlconn.getInputStream();
if(urlconn.getResponseCode()!=200){
//is = urlconn.getErrorStream();
System.out.println("error!!!");
}else{
is=urlconn.getInputStream();
}
byte[] b=new byte[1024];
while(is!=null && is.read(b)!=-1 ){
System.out.println(new String(b));
}
// BufferedReader br=new BufferedReader(new InputStreamReader(is,"ascii"));
// String read_content=new String();
// while((read_content= br.readLine())!=null){
// }
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
博文转自:http://blog.csdn.net/b08514/article/details/20948647