服务端 发送请求,含配置代理

147 阅读1分钟
public CertificationDTO getCertificationData(CertificationDTO paramDTO) {

	logger.trace("getCertificationData start.");
	CloseableHttpClient httpClient = null;
        //配置代理
	String port = "";
	String proxyUsername = "";
	String proxyPassword = "";
	String host = "";
        //
	CertificationDto resultDto = CertificationDAO.selectCertificationData(paramDTO);
	String ceUrl = resultDto.getUrl();
	
        //判断需要连协的服务URL最后是否存在【/】
	if(ceUrl != null) {
		String lastKey = ceUrl.substring(ceUrl.length()-1);
		if(!lastKey.equals("/")) {
			ceUrl = ceUrl + "/";
		}
	}else {
		ceUrl = "";
	}
	String apiUrl = String.format(ceUrl + "%s", "api/AUTH_LOGIN");
	
	RequestConfig config = null;
	HttpPost httpPost = new HttpPost(apiUrl);
        //在http请求中配置代理
	if(!"".equals(host)) {
		HttpHost proxy = new HttpHost(host, Integer.parseInt(port));
		if(!"".equals(proxyUsername) && !"".equals(proxyPassword)) {
                //代理需要用户名密码的场合
			CredentialsProvider provider = new BasicCredentialsProvider();	
			provider.setCredentials(new AuthScope(proxy), new UsernamePasswordCredentials(proxyUsername, proxyPassword));	
			config = RequestConfig.custom().setProxy(proxy).setConnectTimeout(TIMEOUT)
					.setSocketTimeout(TIMEOUT)
					.setConnectionRequestTimeout(TIMEOUT).build();
			httpClient = HttpClients.custom().setDefaultCredentialsProvider(provider).build();
			
		}else {
                //代理不需要用户名密码的场合
			config = RequestConfig.custom().setProxy(proxy).setConnectTimeout(TIMEOUT)
					.setSocketTimeout(TIMEOUT)
					.setConnectionRequestTimeout(TIMEOUT).build();
			httpClient = HttpClients.custom().build();
		}
		httpPost.setConfig(config);
	}else {
		httpClient = HttpClientBuilder.create().build();
	}

	try {
                //添加请求参数
		List<NameValuePair> list = new ArrayList<NameValuePair>();
		list.add(new BasicNameValuePair("id",""));
		list.add(new BasicNameValuePair("pw",""));
		UrlEncodedFormEntity uefEntity = new UrlEncodedFormEntity(list ,"UTF-8");
		httpPost.setEntity(uefEntity);
                //发送请求
		HttpResponse response  = httpClient.execute(httpPost);
		HttpEntity entity = response.getEntity();
		String resp =  EntityUtils.toString(entity,"utf-8");
                //判断状态
		int statusCode = response.getStatusLine().getStatusCode();
		if(statusCode!=200) {
			resultDto.setErrPage(resp);
			return resultDto;
		}
                //取得结果集
		Map<String,String> m = new HashMap<String,String>();
		resp = resp.replaceAll("\"","");
		resp = resp.substring(1,resp.length()-1);
		String[] kvs = resp.split(",");
		for(String kv:kvs){
			m.put(kv.substring(0,kv.indexOf(':')),kv.substring(kv.indexOf(':')+1));
		}
		String message = m.get("message");
		
	} catch (ClientProtocolException e) {
		resultDto.setMessage(e.getMessage());
	} catch (IOException e) {
		resultDto.setMessage(e.getMessage());
	}
	logger.trace("getCertificationData end.");
	return resultDto;
}