服务端发送xml请求java代码示例

/**
 *
 */
package com.autoyol.pay.cmb.core;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.UnrecoverableKeyException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.conn.ConnectionPoolTimeoutException;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

/**
 * @author xxx
 * @function
 * @date 2016年3月23日
 * @version
 */
public class Sender {

    /**
     *
     * @param url
     * @param postDataXML
     * @return
     * @throws Exception
     */
    public static String sendRQ(String url, String postDataXML) throws Exception{
        String result = null;
        OutputStream out = null;
        InputStream is = null;
        ByteArrayOutputStream bos = null;
        HttpURLConnection urlc = null;
        try {
            URL urlacc = new URL(url);
            urlc = (HttpURLConnection) urlacc.openConnection();
            urlc.setConnectTimeout(100000);
            urlc.setReadTimeout(100000);
            urlc.setDoOutput(true);
            urlc.setDoInput(true);
            urlc.setUseCaches(false);
            urlc.setInstanceFollowRedirects(false);//是否自动处理重定向
            urlc.setRequestMethod("POST");

            out = urlc.getOutputStream();
            out.write(postDataXML.getBytes());
            out.flush();
            out.close();

            is = urlc.getInputStream();
            if(is!=null){
                bos = new ByteArrayOutputStream();
                byte[] receiveBuffer = new byte[2048];
                int readBytesSize = is.read(receiveBuffer);
                while(readBytesSize != -1){
                    bos.write(receiveBuffer, 0, readBytesSize);
                    readBytesSize = is.read(receiveBuffer);
                }
                result = new String(bos.toByteArray(), "UTF-8");
//                respXml= ParseUtil.parseXML(reqData,transInfo);
                //xml解析
                System.out.println("result="+result);
            }
        } catch (Exception e) {
//            System.out.println("发送TR1失败");
            e.printStackTrace();
//            logger.error("sendTR1 Exception2:",e);  //sendTR1 Exception2: java.net.NoRouteToHostException: 没有到主机的路由
//            throw e;  //异常再次抛出,解决sendTR1 Exception2: java.net.ConnectException: 连接超时 网络异常的情况。 160201 huangjing
        } finally{
            if(bos != null){
                bos.close();
            }
            if(is != null){
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(out != null){
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(urlc != null){
                urlc.disconnect();
            }
        }
        return result;
    }

    /**
     *
     * @param url
     * @param postDataXML
     * @return
     * @throws IOException
     * @throws KeyStoreException
     * @throws UnrecoverableKeyException
     * @throws NoSuchAlgorithmException
     * @throws KeyManagementException
     */
    public static String sendPost(String url, String postDataXML) throws IOException, KeyStoreException, UnrecoverableKeyException, NoSuchAlgorithmException, KeyManagementException {
        String result = null;
        HttpPost httpPost = new HttpPost(url);
        System.out.println("API,POST过去的数据是:" + postDataXML);
        //得指明使用UTF-8编码,否则到API服务器XML的中文不能被成功识别
        StringEntity postEntity = new StringEntity(postDataXML, "UTF-8");
        httpPost.addHeader("Content-Type", "text/xml");
        httpPost.setEntity(postEntity);
        //设置请求器的配置
        CloseableHttpClient httpClient = HttpClients.custom().build();
//        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        //根据默认超时限制初始化requestConfig
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(10000).setConnectTimeout(30000).build();
        httpPost.setConfig(requestConfig);
        System.out.println("executing request:" + httpPost.getRequestLine());
        try {
            HttpResponse response = httpClient.execute(httpPost);
            int httpStatusCode = response.getStatusLine().getStatusCode();
            if (httpStatusCode == HttpStatus.SC_OK) {
                HttpEntity entity = response.getEntity();
                result = EntityUtils.toString(entity, "UTF-8");
                System.out.println("result="+result);
            }else{
                System.err.println("Error,httpStatusCode is ‘{"+httpStatusCode+"}‘");
            }
        } catch (ConnectionPoolTimeoutException e) {
            System.err.println("http get throw ConnectionPoolTimeoutException(wait time out)");
        } catch (ConnectTimeoutException e) {
            System.err.println("http get throw ConnectTimeoutException");
        } catch (SocketTimeoutException e) {
            System.err.println("http get throw SocketTimeoutException");
        } catch (Exception e) {
            System.err.println("http get throw Exception");
        } finally {
            httpPost.abort();
        }
        return result;
    }

}
时间: 2024-10-15 16:08:12

服务端发送xml请求java代码示例的相关文章

HttpClient服务端发送http请求

本来以为对跨域问题的处理已经比较熟练了.可以通过jsonp.document.domain+iframe.window.name.window.postMessage.服务器上设置代理页面来解决.但还是遇到了难题dva封装的request: 1.robe-ajax用它来调其他网站的api,会报跨域问题怎么设置也没用. 2.fetch可以通过设置mode:no-cors来解决跨域,但到checkStatus时会报错,network能看到response. 3.jq ajax设置dataType:j

jQuery表单 Ajax向PHP服务端发送文件请求并返回数据

ImageAjaxUpLoad.htm <!DOCTYPE html> <head> <meta charset='utf-8'> <title></title> <script src="jquery-1.6.1.min.js" type="text/javascript"></script> <script src="jquery.form.js" ty

jQuery通过Ajax向PHP服务端发送请求并返回JSON数据

ON(JavaScript Object Notation) 是一种轻量级的数据交换格式.易于人阅读和编写,同时也易于机器解析和生成.JSON在前后台交互的过程中发挥着相当出色的作用.请接着往下看教程. XHTML  <ul id="userlist">    <li><a href="#" rel="1">张三</a></li>    <li><a href=&quo

Hessian客户端向服务端发送请求头

Hessian客户端向服务端发送数据 场景:项目日志Token处理,即用户发送一个请求时生成一个日志Token,该Token从各个服务之间传递,并使用该Token记录日志,直至请求结束.可以根据该Token定位所有日志. 问题:由于目前项目使用Hessian协议,所有Token必须使用Hessian传递.查阅相关资料,发现可以请求头传递数据. 解决方法:定义与线程相关的请求头上下文,在客户端发送请求之前,增加请求头.服务端获取请求时,从请求中解决请求头,并放入请求头上下文中,供服务端使用. 实现

通过http请求传递xml流和接收xml流的代码示例

通过http请求传递xml流和接收xml流的代码示例 //1.在servlet中post一个xml流:import java.io.OutputStreamWriter;import org.jdom.Document;import org.jdom.Document; public void doPost(HttpServletRequest request, HttpServletResponse response)    throws ServletException, IOExcepti

Ajax发送XML请求案例

如果请求参数较多,而且请求参数的结构关系复杂,则可以考虑发送XML请求.XML请求的实质还是POST请求,只是在发送请求的客户端页面将请求参数封装成XML字符串的形式,服务器端则负责解析该XML字符串.当然,服务器获取到XML字符串后,可借助于dom4j或JDOM等工具来解析. 程序清单:Ajax02request/xml/second.jsp 1 <%@ page contentType="text/html; charset=UTF-8" language="jav

ASP.NET之通过JS向服务端(后台)发出请求(__doPostBack is undefined)

ASP.NET回发数据是通过函数__doPostBack来实现的,该函数在添加了服务端控件,并将AutoPostBack设置为true之后,将自动生成,具体可以参看下面的图. 同时还会生成隐藏控件,其ID为__EVENTTARGET和__EVENTARGUMENT,前一个是用于存放key的,后一个用于存放参数的. 所以在后台通过Request.Form来获取所要的数据,test.aspx.cs代码如下 using System; using System.Collections.Generic;

TCP练习2: 客户端给服务端发送文本,服务端将文本转成大写再返回给客户端

import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.InetAddress; import java.net.ServerSocket; import java.net.Socket; import java.net.UnknownHostException; import org.junit.Test; /* * 客户端给服务端发送文本,服务端将

XMLHttpRequest发送XML请求

1.前言 对于请求参数为大师key-value对的情形,笔者更加倾向于使用简单的POST请求.但对于某些极端的表形,如请求参数特别多,而且请求参数的结构关系复杂,则可以考虑发送XML请求.XML请求的实质还是POST请求,只是在发送请求的客户产端页面将请求参数封装成XML字符串的形式,服务器则负责解析XML字符串.当然,服务器获取到XML字符串后,可借助dom4j或JDOM等工具来解析. 2.例子 这个例子还是跟前面所讲的一样,通过左边的点击国家,然后点击"发送",右边 就可以看到国家