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