java 发送http请求

 

 

在这里介绍一个关于发送和接受http的示例,关于URL和HttpURLConnection类请参考jdk.

 


String method 
=   " POST " ;
String content 
=   " dd " ;
URL url 
=   new  URL(http: // 192.168.100.77/test.jsp);

HttpURLConnection urlConnection 
=  (HttpURLConnection) url.openConnection();

urlConnection.setRequestMethod(method);
urlConnection.setDoOutput(
true ); // URL 连接可用于输入和/或输出
urlConnection.setDoInput( true ); // URL 连接可用于输入和/或输出
urlConnection.setUseCaches( false );

// 设置http头
urlConnection.addRequestProperty( " POST " , " /  HTTP/1.1 " );
urlConnection.addRequestProperty(
" Content-Typeapplication/client " );
urlConnection.addRequestProperty(
" Content-Lengt " , " 1000 " );

// 设置包体
urlConnection.getOutputStream().write(content.toString().getBytes());
urlConnection.getOutputStream().flush();
urlConnection.getOutputStream().close();


// 取得返回包体
            InputStream in  =  urlConnection.getInputStream();
            BufferedReader bufferedReader 
=   new  BufferedReader(
                    
new  InputStreamReader(in)); // 取得返回内容
            httpResponser.contentCollection  =   new  Vector < String > ();
            StringBuffer temp 
=   new  StringBuffer();
            String line 
=  bufferedReader.readLine();
            System.out.println(
" lenth: " + urlConnection.getContentLength());
            
while  (line  !=   null {
                httpResponser.contentCollection.add(line);
                temp.append(line).append(
" ");
                line 
= bufferedReader.readLine();
            }


// 取得返回http头信息
          String content - type  =  urlConnection.getHeaderField( " Content-Type " );
          String contentLenth 
=  urlConnection.getHeaderField( " Content-Length " );
          Sring code 
=  urlConnection.getHeaderField( " errorcode " );

 

 

你可能感兴趣的:(技术总结)