java的http通信

一.使用URlConnection


//传入的数据为xml格式字符串
public static String sendPosts(String url, String param) throws DocumentException {
System.out.println("=========发送报文=========="+"\n"+Xmlutil.getxml());
 
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection conn = realUrl.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)");
            
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            
            // 获取URLConnection对象对应的输出流
            out = new PrintWriter(conn.getOutputStream());
            // 发送请求参数
            out.print(param);
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader( new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("发送 POST 请求出现异常!"+e);
            e.printStackTrace();
        }
        //使用finally块来关闭输出流、输入流
        finally{
            try{
                if(out!=null){
                    out.close();
                }
                if(in!=null){
                    in.close();
                }
            }
            catch(IOException ex){
                ex.printStackTrace();
            }
        }
        
        System.out.println();
        System.out.println("=========响应报文=========="+"\n"+xmlprint(result));
        
        
        return result;
    }





二.使用HTTPURLConnection(为URLConnection的子类)

public String Post(){

try {
 
Xmlutil xml=new Xmlutil();

String xmlstr=xml.getxml();
System.out.println("==========发送报文============"+"\n"+xmlstr);
 
        
         // 创建url资源
         URL url = new URL(url);
         // 建立http连接
         HttpURLConnection conn = (HttpURLConnection) url.openConnection();
         // 设置允许输出
         conn.setDoOutput(true);


         conn.setDoInput(true);


         // 设置不用缓存
         conn.setUseCaches(false);
         // 设置传递方式
         conn.setRequestMethod("POST");
         // 设置维持长连接
         conn.setRequestProperty("Connection", "Keep-Alive");
         // 设置文件字符集:
         conn.setRequestProperty("Charset", "UTF-8");
         //转换为字节数组
         byte[] data = xmlstr.getBytes();
         // 设置文件长度
         conn.setRequestProperty("Content-Length", String.valueOf(data.length));
         // 设置文件类型:
         conn.setRequestProperty("contentType", "text/xml");
         // 开始连接请求
         conn.connect();
         OutputStream  out = conn.getOutputStream();     
         // 写入请求的字符串
         out.write(data);
         out.flush();
         out.close();


         System.out.println(conn.getResponseCode());


         // 请求返回的状态
         if (conn.getResponseCode() == 200) {
             System.out.println("连接成功");
             // 请求返回的数据
             InputStream in = conn.getInputStream();
             String a = null;
             try {
                 byte[] data1 = new byte[in.available()];
                 in.read(data1);
                 // 转成字符串
                 a = new String(data1);
                 
                 System.out.println("========================响应报文========================"+"\n"+xmlprint(a));
                 return a;
             } catch (Exception e1) {
                 // TODO Auto-generated catch block
                 e1.printStackTrace();
             }
         } else {
             System.out.println("no++");
         }


     } catch (Exception e) {


     }
return null;
 
}





三.使用HTTPClient(最简洁的方式)

//使用httpclient进行http通信(采用HttpClient4.3以上版本)
    public String sendXMLDataByPost(String url, String xmlData) throws Exception {
    
    System.out.println("==================发送报文================="+"\n"+Xmlutil.getxml());
    //1.创建httpclient对象
    HttpClient httpclient=HttpClients.createDefault();
    //2.创建POST请求
        HttpPost post = new HttpPost(url);  
        //3.添加http头信息
//        post.addHeader("Content-Type", "text/xml;charset=UTF-8");
        //4.创建消息实体
        StringEntity stringEntity=new StringEntity(xmlData,"utf-8");
        //解决中文乱码问题
        stringEntity.setContentEncoding("utf-8");
        
        //5.向post请求中添加消息实体
        post.setEntity(stringEntity);
        
        //手动读取响应
//        HttpResponse response=httpclient.execute(post);
//        HttpEntity httpEntity=response.getEntity();
//        String result=EntityUtils.toString(httpEntity, "utf-8");
        
        //响应器处理器
//        ResponseHandler<String> responseHandler= new ResponseHandler<String>() {
//
// @Override
// public String handleResponse(HttpResponse response)
// throws ClientProtocolException, IOException {
// 
// int status=response.getStatusLine().getStatusCode();
// 
// if(status>=200 && status<300){
// HttpEntity entity=response.getEntity();
// //三目运算符
// return entity != null ? EntityUtils.toString(entity) : null; 
// }else{
// throw new ClientProtocolException("Unexpected response status: " + status);
// }
// 
// }
//        
// };
        //自动读取响应
        ResponseHandler<String> responseHandler= new BasicResponseHandler();
          
String result=httpclient.execute(post, responseHandler);
        
        System.out.println("==================响应报文================="+"\n"+xmlprint(result));
        return result;  
    }
关于响应内容可以有三种处理方式:EntityUtils、ResponseHandler、BasicResponseHandler





猜你喜欢

转载自blog.csdn.net/qq_35053757/article/details/79241514