/**
*
*/
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;
} }

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

  1. HttpClient服务端发送http请求

    本来以为对跨域问题的处理已经比较熟练了.可以通过jsonp.document.domain+iframe.window.name.window.postMessage.服务器上设置代理页面来解决.但还 ...

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

    ImageAjaxUpLoad.htm <!DOCTYPE html> <head> <meta charset='utf-8'> <title>< ...

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

    Query通过Ajax向PHP服务端发送请求并返回JSON数据 服务端PHP读取MYSQL数据,并转换成JSON数据,传递给前端Javascript,并操作JSON数据.本文将通过实例演示了jQuer ...

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

    SON(JavaScript Object Notation) 是一种轻量级的数据交换格式.易于人阅读和编写,同时也易于机器解析和生成.JSON在前后台交互的过程中发挥着相当出色的作用.请接着往下看教 ...

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

    通过http请求传递xml流和接收xml流的代码示例 //1.在servlet中post一个xml流:import java.io.OutputStreamWriter;import org.jdom ...

  6. c# .NET RSA结合AES加密服务端和客户端请求数据

    这几天空闲时间就想研究一下加密,环境是web程序,通过js请求后台返回数据,我想做的事js在发送请求前将数据加密,服务端收到后解密,待服务端处理完请求后,将处理结果加密返回给客户端,客户端在解密,于是 ...

  7. 极光推送JAVA代码示例

    一. 准备工作 1. 登录极光推送官网https://www.jpush.cn/,注册账号并登录 2. 创建应用 创建应用过程,详见百度经验:http://jingyan.baidu.com/arti ...

  8. 利用laravel-echo主动向服务端发送消息,实现在线状态管理

    之前在网上翻了半天,也没有找到关于如何 通过laravel-echo主动发送消息 和 在laravel-websockets中自定义控制器 的文章或教程.无奈之下只能翻laravel-echo和lar ...

  9. Kafka技术内幕 读书笔记之(六) 存储层——服务端处理读写请求、分区与副本

    如下图中分区到 日 志的虚线表示 : 业务逻辑层的一个分区对应物理存储层的一个日志 . 消息集到数据文件的虚线表示 : 客户端发送的消息集最终会写入日志分段对应的数据文件,存储到Kafka的消息代理节 ...

随机推荐

  1. Tostring记录,方便自己查看

    C 货币 2.5.ToString("C") ¥2.50 D 十进制数 25.ToString("D5") 00025 E 科学型 25000.ToString ...

  2. ios 总结

    1 ocoa Touch Layer{ App Extensions https://developer.apple.com/library/ios/documentation/General/Con ...

  3. Ajax 异步调用代码

    function jsAjax() { var Con; var XmlRequset; var AjaxContent; //返回内容 if (window.XMLHttpRequest) { // ...

  4. 7.FPGA中的同步复位与异步复位

    1.异步复位 always @ ( posedge sclk or negedge s_rst_n ) if ( !s_rst_n ) d_out <= 1'b0; else d_out < ...

  5. Python实现kNN(k邻近算法)

    Python实现kNN(k邻近算法) 运行环境 Pyhton3 numpy科学计算模块 计算过程 st=>start: 开始 op1=>operation: 读入数据 op2=>op ...

  6. java判断某个字符串包含某个字符串的个数

    /** * 判断str1中包含str2的个数 * @param str1 * @param str2 * @return counter */ public static int countStr(S ...

  7. 在数据表中添加一个字段的SQL语句怎么写

    如果要在数据表中添加一个字段,应该如何表示呢?下面就为您介绍表添加字段的SQL语句的写法,希望可以让您对SQL语句有更深的认识.   通用式: alter table [表名] add [字段名] 字 ...

  8. c/c++中主线程退出,子线程也会退出

    #include <windows.h> #include <process.h> /* _beginthread, _endthread */ #include <io ...

  9. 点亮led【转载】

    http://linux-sunxi.org/Cubieboard/Programming/StatusLEDs Accessing the status LEDs The Cubieboard ha ...

  10. Could not load file or assembly 'Microsoft.Office.Interop.Word, Version=14.0

    参考地址一:点击这里 参考地址二:点击这里 解决方法: 使用office COM元件,电脑里必须要有相对应的版本,比如 Excel 14.0是对应Excel 2010 Excel 12.0是对应Exc ...