1.使用java原生HttpURLConnection访问web服务。
public class RTBClient { private String url = <a target=_blank href="http://localhost">http://localhost</a>; private String port = "8080"; private String path = "/RTBServer/RTBServer";
public RTBClient() {} public Result[] get(DspContext dc) { if (null == dc ) { return null; } URL url = null; HttpURLConnection urlConn = null; try { url = new URL(this.url + ":" + this.port + this.path); urlConn = (HttpURLConnection) url.openConnection(); urlConn.setDoOutput(true); urlConn.setDoInput(true); urlConn.setUseCaches(false); urlConn.setRequestProperty("Content-type", "application/x-java-serialized-object"); urlConn.setRequestMethod("POST"); urlConn.connect(); } catch (MalformedURLException e1) { e1.printStackTrace(); } catch (ProtocolException e1) { e1.printStackTrace(); } catch (IOException e1) { e1.printStackTrace(); } try { OutputStream outStrm = urlConn.getOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(outStrm); oos.writeObject(dc); oos.flush(); oos.close(); } catch (IOException e1) { e1.printStackTrace(); } Result[] result; try { InputStream inStrm = urlConn.getInputStream(); ObjectInputStream ois = new ObjectInputStream(inStrm); result = (Result[]) (ois.readObject()); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (EOFException e) { e.printStackTrace(); } catch (IOException e1) { e1.printStackTrace(); } urlConn.disconnect(); return null; } }
2.使用Apache的HttpClient包访问web服务。
public class RtbClient { private String address = null; private int connReqTimeout = 5000; private int connTimeout = 5000; private int soTimeout = 5000; private int maxConn = 100; private HttpClient httpClient = null; PoolingHttpClientConnectionManager connManager = null; public RtbClient(String address, int connReqTimeout, int connTimeout, int soTimeout, int maxConn) { this.address = address; this.connReqTimeout = connReqTimeout; this.connTimeout = connTimeout; this.soTimeout = soTimeout; this.maxConn = maxConn; RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(this.connTimeout) .setConnectionRequestTimeout(this.connReqTimeout) .setSocketTimeout(this.soTimeout).build(); this.connManager = new PoolingHttpClientConnectionManager(); this.connManager.setMaxTotal(this.maxConn); this.httpClient = HttpClientBuilder.create() .setConnectionManager(this.connManager).setDefaultRequestConfig(requestConfig).build(); } public void sendReq(String str) { HttpPost post = new HttpPost(address);
HttpEntity entity = new StringEntity(str);
post.setEntity(entity);
HttpResponse response; try { response = this.httpClient.execute(post); if (null != response) { System.out.println(response.getStatusLine().getStatusCode()); } } catch (HttpHostConnectException e) { logger.error("client can not connect server!", e); e.printStackTrace(); } catch (Exception e) { logger.error("rtb client get method invoke exception!", e); e.printStackTrace(); } return; } }
时间: 2024-10-05 03:04:35