请求webService的几种方式

来源:互联网 发布:cepii世界贸易数据库 编辑:程序博客网 时间:2024/05/22 15:30

第一种,使用HttpURLConnection,post请求。需要传入路径以及xml报文,返回结果报文。

public String sendPost(String url, String param) {
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        OutputStream ous = null;
        try {
            URL realUrl = new URL(url);
            HttpURLConnection conn = (HttpURLConnection) realUrl.openConnection();
            conn.setRequestMethod("POST");
            conn.setAllowUserInteraction(true);
            conn.setRequestProperty("content-type", "application/xml");
            conn.setDoOutput(true);
            conn.setDoInput(true);
            ous = conn.getOutputStream();
            ous.write(param.getBytes());
            ous.flush();
            in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        }catch (Exception e) {
            e.printStackTrace();
        }
        finally{
            try{
                if(ous!=null){
                    ous.close();
                }
                if(in!=null){
                    in.close();
                }
            }
            catch(IOException ex){
                ex.printStackTrace();
            }
        }
        return result;
    }

第二种,使用client方式,post请求,我使用的是 httpclient-cache-4.1.2.jar,httpcore-4.3.jar,httpmime-4.3.1.jar。

public static String doPostSoap(String postUrl, String soapXml, String soapAction) {  
         String retStr = "";  
         // 创建HttpClientBuilder  
         HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();  
         // HttpClient  
         CloseableHttpClient closeableHttpClient = httpClientBuilder.build();  
         HttpPost httpPost = new HttpPost(postUrl);  
                 //  设置请求和传输超时时间  
         RequestConfig requestConfig = RequestConfig.custom()  
                 .setSocketTimeout(socketTimeout)  
                 .setConnectTimeout(connectTimeout).build();  
         httpPost.setConfig(requestConfig);  
         try {  
             httpPost.setHeader("Content-Type", "text/xml;charset=UTF-8");  
             httpPost.setHeader("SOAPAction", soapAction);  
             StringEntity data = new StringEntity(soapXml,Charset.forName("UTF-8"));  
             httpPost.setEntity(data);  
             CloseableHttpResponse response = closeableHttpClient.execute(httpPost);  
             HttpEntity httpEntity = response.getEntity();  
             if (httpEntity != null) {  
                 retStr = EntityUtils.toString(httpEntity, "UTF-8");  
                 System.out.println(retStr);
             }  
             // 释放资源  
             closeableHttpClient.close();  
         }catch (Exception e) {  
         }  
         return retStr;  
     }
 }


原创粉丝点击