http通信实现方式

1. client

1.1 使用apache client

重发参数设置:不重发

httpClient.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(0, false));

import java.io.IOException;

import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
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;

public class HttpClient {
	public String httpClientInvoke(String request) {
		int maxTimeOut = 30000;
		// 请求参数设置
		RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(maxTimeOut).setConnectTimeout(maxTimeOut).setSocketTimeout(maxTimeOut).build();

		CloseableHttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(requestConfig).build();
		StringEntity stringEntity = new StringEntity(String.valueOf(request), "GBK");
		stringEntity.setContentEncoding("GBK");
		stringEntity.setContentType("text/xml; charset=GBK");
		HttpPost httpPost = new HttpPost("http://up.meicano.com");
		httpPost.setHeader("Content-Type", "application/xmlstream");
		httpPost.setEntity(stringEntity);
		String rspXml = "";
		CloseableHttpResponse response = null;
		HttpEntity httpEntity = null;
		try {
			response = httpClient.execute(httpPost);
			httpEntity = response.getEntity();
			if (httpEntity != null) {
				rspXml = EntityUtils.toString(httpEntity, "GBK");
			}

		} catch (ClientProtocolException e) {
			System.err.println("协议异常" + e.getStackTrace());
		} catch (IOException e) {
			System.err.println("IO异常" + e.getStackTrace());
		} finally {
			try {
				EntityUtils.consume(httpEntity);
				response.close();
				httpClient.close();
			} catch (IOException e) {
				System.err.println("释放资源异常" + e.getStackTrace());
			}
		}
		return rspXml;
	}
}

 

2. server

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值