http通訊實現方式
阿新 • • 發佈:2019-02-04
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; } }