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

时间:2024-08-18 09:03:20
/**
*
*/
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;
} }