http发送http报文

  1. package com.lkt.jdk;  
  2.   
  3. import java.io.BufferedInputStream;  
  4. import java.io.BufferedReader;  
  5. import java.io.DataOutputStream;  
  6. import java.io.IOException;  
  7. import java.io.InputStream;  
  8. import java.io.InputStreamReader;  
  9. import java.net.HttpURLConnection;  
  10. import java.net.URL;  
  11.   
  12. public class GetHttp {  
  13.   
  14.     public static String getWebContent()throws IOException{  
  15.           
  16.         //创建URL,协议、ip、端口、访问的页面  
  17.         URL url=new URL("HTTP","192.168.22.209",7001,"/Request_USER_LOGIN");  
  18.         //创建HttpURLConnection 对象  
  19.         HttpURLConnection conn=(HttpURLConnection)url.openConnection();  
  20.         //设置请求方式POST  
  21.         conn.setRequestMethod("POST");  
  22.         conn.setRequestProperty("Content-Type", "application/xml");  
  23.         conn.setRequestProperty("Connection", "Keep-Alive");  
  24.           
  25.         //请求的数据  
  26.         String xml="<?xml version="1.0" encoding="UTF-8"?> "+  
  27.         "<HTTP_XML EventType="Request_USER_LOGIN" TargetSyscode="" RequestId="" TransactionId="">"+   
  28.         "   <Item Name="admin"  Password="670b14728ad9902aecba32e22fa4f6bd" UserIp="" Port="" BusinessSysCode=""/>"+  
  29.         "</HTTP_XML>";  
  30.         //数据长度  
  31.         conn.setRequestProperty("Content-Length",xml.length()+"");  
  32.         //设置输入和输出流  
  33.         conn.setDoOutput(true);  
  34.         conn.setDoInput(true);  
  35.         //将参数输出到连接  
  36.         //使用这种方式,我在本地执行没有问题,在weblogic下出现过错误  
  37.         //java.net.ProtocolException: Did not meet stated content length of OutputStream:  you wrote 0 bytes and I was expecting  you to write exactly 241 bytes!!!  
  38.         //我使用第二中方法就可以了  
  39.         /*方法一 
  40.         conn.getOutputStream().write(xml.getBytes("UTF-8")); 
  41.         conn.getOutputStream().flush(); 
  42.         conn.getOutputStream().close(); 
  43.         */  
  44.         /* 
  45.          * 方法二 */  
  46.         DataOutputStream dos=new DataOutputStream(conn.getOutputStream());  
  47.         dos.writeBytes(xml);  
  48.         dos.flush();  
  49.         dos.close();  
  50.         //得到HTTP响应码  
  51.         int code=conn.getResponseCode();  
  52.         InputStream is=conn.getInputStream();  
  53.           
  54.         //获取返回报文  
  55.         BufferedReader bis=new BufferedReader(new InputStreamReader(is));  
  56.         StringBuffer sb=new StringBuffer();  
  57.         String temp="";  
  58.         while((temp=bis.readLine())!=null){  
  59.             sb.append(temp+" ");  
  60.         }  
  61.         return null;  
  62.           
  63.     }  
  64.     public static void main(String[] args)throws Exception {  
  65.         getWebContent();  
  66.     }  
  67. }  
原文地址:https://www.cnblogs.com/zszitman/p/4565003.html