Servlet怎么把参数传递到sendPostHttpRequestWithTimeOut,然后再返回数据?
public class urlstar extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
JSONObject js = new JSONObject();
js.put("user", "admin");
js.put("password", "654321");
try {
HttpClientUtil h = new HttpClientUtil();
String result = sendPostHttpRequestWithTimeOut("http://aaatest:5015/getToken", js.toString(), null, 1000);
//System.out.println(result);
} catch (Exception e) {
e.printStackTrace();
}
JSONObject jsonObject2 = new JSONObject();
jsonObject2.put("chestate", getlogin);
response.getWriter().write(jsonObject2.toString());
}
}
Servlet怎么把参数传递到下面sendPostHttpRequestWithTimeOut,然后再返回数据?
import org.apache.http.HttpEntity;
import org.apache.http.HttpException;
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.client.protocol.HttpClientContext;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.config.SocketConfig;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.client.StandardHttpRequestRetryHandler;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.protocol.HTTP;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;
import javax.net.ssl.SSLContext;
import java.io.IOException;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Map;
import java.util.Objects;
/**
* @Description : httpComponents httpclient工具
* @Version : V1.0.0
* @Date : 2023/1/3 17:46
*/
public class HttpClientUtil {
/**
* 忽视所有证书验证-使用org.apache.httpcomponents 4.5版本
*
* @return
*/
public static CloseableHttpClient trustAllCertsHttpClient() throws NoSuchAlgorithmException, KeyStoreException, KeyManagementException {
SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, new TrustStrategy() {
// 忽略证书校验
@Override
public boolean isTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
return true;
}
}).build();
SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContext, new String[]{"TLSv1.2"}, null, NoopHostnameVerifier.INSTANCE);
final Registry socketFactoryRegistry = RegistryBuilder.create()
.register("http", PlainConnectionSocketFactory.getSocketFactory())
.register("https", sslConnectionSocketFactory).build();
// 5秒超时
RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(5000)
.setSocketTimeout(10000).setConnectTimeout(10000).build();
SocketConfig socketConfig = SocketConfig.custom().setSoTimeout(5000).build();
PoolingHttpClientConnectionManager cm =
new PoolingHttpClientConnectionManager(socketFactoryRegistry);
cm.setMaxTotal(300);
// 单路由最大并发数
cm.setDefaultMaxPerRoute(30);
return HttpClients.custom()
.setDefaultRequestConfig(requestConfig)
.setRetryHandler(new StandardHttpRequestRetryHandler())
.setDefaultSocketConfig(socketConfig).setConnectionManager(cm).build();
}
public static String sendPostHttpRequestWithTimeOut(String reqURL, String param, Map headerMap, int readTimeout) throws HttpException {
String result = "-1";
HttpPost httpPost = new HttpPost(reqURL);
httpPost.setHeader(HTTP.CONTENT_TYPE, "application/json; charset=" + "UTF-8");
CloseableHttpResponse response = null;
try {
if (param != null) {
StringEntity entity = new StringEntity(param, "UTF-8");
httpPost.setEntity(entity);
if (!Objects.isNull(headerMap) && headerMap.size() != 0) {
for (Map.Entry entry : headerMap.entrySet()) {
httpPost.addHeader(entry.getKey(), entry.getValue());
}
}
}
RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(1000).setConnectTimeout(1000)
.setSocketTimeout(readTimeout).build();
httpPost.setConfig(requestConfig);
response = trustAllCertsHttpClient().execute(httpPost, HttpClientContext.create());
HttpEntity entity = response.getEntity();
if (null != entity) {
result = EntityUtils.toString(entity, ContentType.getOrDefault(entity).getCharset());
EntityUtils.consume(entity);
}
} catch (Exception e) {
throw new HttpException("请求通信[" + reqURL + "]时读取超时,堆栈轨迹如下:", e);
} finally {
if (response != null) {
try {
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (httpPost != null) {
httpPost.releaseConnection();
}
}
return result;
}
}
从request中拿参数啊。
request.getParameter("参数名")
严重: Servlet.service() for servlet [cn.Serlvet.shiyan] in context with path [/Bigdata] threw exception [Servlet execution threw an exception] with root cause
java.lang.ClassNotFoundException: org.apache.http.ssl.TrustStrategy
at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1352)
at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1180)
at cn.Serlvet.shiyan.doPost(shiyan.java:39)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:648)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:292)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
at cn.filter.EncodingFilter.doFilter(EncodingFilter.java:22)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:212)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:94)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:496)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:141)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:620)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:502)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1156)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:684)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1539)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1495)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Unknown Source)