远程调用代码

1、HttpClient

package com.dtb.admin.util;



import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
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.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import javax.net.ssl.*;
import java.io.*;
import java.net.URI;
import java.net.URL;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.*;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;

public class HttpClientUtil {

   public static String doGet(String url, Map<String, String> param) {

      // 创建Httpclient对象
      CloseableHttpClient httpclient = HttpClients.createDefault();

      String resultString = "";
      CloseableHttpResponse response = null;
      try {
         // 创建uri
         URIBuilder builder = new URIBuilder(url);
         if (param != null) {
            for (String key : param.keySet()) {
               builder.addParameter(key, param.get(key));
            }
         }
         URI uri = builder.build();

         // 创建http GET请求
         HttpGet httpGet = new HttpGet(uri);

         // 执行请求
         response = httpclient.execute(httpGet);
         // 判断返回状态是否为200
         if (response.getStatusLine().getStatusCode() == 200) {
            resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
         }
      } catch (Exception e) {
         e.printStackTrace();
      } finally {
         try {
            if (response != null) {
               response.close();
            }
            httpclient.close();
         } catch (IOException e) {
            e.printStackTrace();
         }
      }
      return resultString;
   }

   public static String doGet(String url) {
      return doGet(url, null);
   }

   public static String doPost(String url, Map<String, String> param) {
      // 创建Httpclient对象
      CloseableHttpClient httpClient = HttpClients.createDefault();
      CloseableHttpResponse response = null;
      String resultString = "";
      try {
         // 创建Http Post请求
         HttpPost httpPost = new HttpPost(url);
         // 创建参数列表
         if (param != null) {
            List<NameValuePair> paramList = new ArrayList<>();
            for (String key : param.keySet()) {
               paramList.add(new BasicNameValuePair(key, param.get(key)));
            }
            // 模拟表单
            UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList,"utf-8");
            httpPost.setEntity(entity);
         }
         // 执行http请求
         response = httpClient.execute(httpPost);
         resultString = EntityUtils.toString(response.getEntity(), "utf-8");
      } catch (Exception e) {
         e.printStackTrace();
      } finally {
         try {
            response.close();
         } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
         }
      }

      return resultString;
   }

   public static String doPost(String url) {
      return doPost(url, null);
   }
   
   public static String doPostJson(String url, String json) {
      // 创建Httpclient对象
      CloseableHttpClient httpClient = HttpClients.createDefault();
      CloseableHttpResponse response = null;
      String resultString = "";
      try {
         // 创建Http Post请求
         HttpPost httpPost = new HttpPost(url);
         // 创建请求内容
         StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
         httpPost.setEntity(entity);
         // 执行http请求
         response = httpClient.execute(httpPost);
         resultString = EntityUtils.toString(response.getEntity(), "utf-8");
      } catch (Exception e) {
         e.printStackTrace();
      } finally {
         try {
            response.close();
         } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
         }
      }

      return resultString;
   }
   
   public static final String GET = "GET";
   public static final String POST = "POST";
   public static final String HEAD = "HEAD";
   public static final String OPTIONS = "OPTIONS";
   public static final String PUT = "PUT";
   public static final String DELETE = "DELETE";
   public static final String TRACE = "TRACE";
   private static Map<String, SSLSocketFactory> SSLSocketFactoryPool = new ConcurrentHashMap<>();//签名缓存
   private static Map<String, URL> URLPool = new ConcurrentHashMap<>();//URL链接缓存
   /**
    * 处理https GET/POST请求 
    * 请求地址、请求方法、参数 
    * @param requestUrl 请求参数(为使用连接池处理,请不要在url中携带参数,并且保证同接口url唯一)
    * @param requestMethod GET/POST请求 等
    * @param param 参数
    * @return
    * @throws Exception 
    */
   public static String httpsRequest(String requestUrl,String requestMethod, Map<String, Object> param) throws Exception{
      if (!requestUrl.startsWith("https")) {
         if ("GET".equals(requestMethod)) {
            return URLConnectionUtil.doGet(requestUrl, param);
         }else{
            return URLConnectionUtil.doPost(requestUrl, param);
         }
      }
      requestUrl = requestUrl.trim();
      StringBuffer outputStrBf = new StringBuffer();
      //解析参数
      if (param != null&&param.size()>0&&!GET.equals(requestMethod)) {
         Set<Entry<String, Object>> entrySet = param.entrySet();
         Iterator<Entry<String, Object>> iterator = entrySet.iterator();
         while (iterator.hasNext()) {
            Entry<String, Object> next = iterator.next();
            if (next.getValue() != null) {
               outputStrBf.append("&"+next.getKey()+"="+next.getValue().toString());
            }
         }
      }else if (param != null&&GET.equals(requestMethod)) {
         Set<Entry<String, Object>> entrySet = param.entrySet();
         Iterator<Entry<String, Object>> iterator = entrySet.iterator();
         boolean isStart = true;
         while (iterator.hasNext()) {
            Entry<String, Object> next = iterator.next();
            if (next.getValue() != null) {
               if (!requestUrl.contains("?")&&isStart) {
                  outputStrBf.append("?"+next.getKey()+"="+next.getValue().toString());
                  isStart = false;
               }else{
                  outputStrBf.append("&"+next.getKey()+"="+next.getValue().toString());
               }
            }
         }
         
      }
       StringBuffer buffer=null;  
       URL url= null;
       SSLSocketFactory ssf= null;
       try{  
          if (URLPool.size()>0&&URLPool.containsKey(requestUrl)) {
             url = URLPool.get(requestUrl);
             ssf = SSLSocketFactoryPool.get(requestUrl);
         }else{
            //创建SSLContext  
             SSLContext sslContext=SSLContext.getInstance("SSL");  
             TrustManager[] tm={new MyX509TrustManager()};  
             //初始化  
             sslContext.init(null, tm, new java.security.SecureRandom());;  
             //获取SSLSocketFactory对象  
             ssf=sslContext.getSocketFactory();  
             if (GET.equals(requestMethod)) {
                url=new URL(requestUrl+outputStrBf.toString());  
             }else{
                url=new URL(requestUrl);  
             }
             
         }
          HttpsURLConnection conn =(HttpsURLConnection)url.openConnection();  
          conn.setDoOutput(true);  
          conn.setDoInput(true);  
          conn.setUseCaches(false);  
          conn.setRequestMethod(requestMethod);  
          //设置当前实例使用的SSLSoctetFactory  
          conn.setSSLSocketFactory(ssf);  
          conn.connect();  
          if (!GET.equals(requestMethod)) {
             //往服务器端写内容  
             if(null!=outputStrBf){  
                 OutputStream os=conn.getOutputStream();  
                 os.write(outputStrBf.toString().getBytes("utf-8"));  
                 os.close();  
             }  
          }
            
          //读取服务器端返回的内容  
          InputStream is=conn.getInputStream();  
          InputStreamReader isr=new InputStreamReader(is,"utf-8");  
          BufferedReader br=new BufferedReader(isr);  
          buffer=new StringBuffer();  
          String line=null;  
          while((line=br.readLine())!=null){  
              buffer.append(line);  
          }  
          //进行链接缓存
          SSLSocketFactoryPool.put(requestUrl, ssf);
          URLPool.put(requestUrl, url);
       }catch(Exception e){  
           e.printStackTrace();  
       }  
       return buffer==null?"":buffer.toString();  
   } 
}
class MyX509TrustManager implements X509TrustManager {  
     
    @Override  
    public void checkClientTrusted(X509Certificate[] chain, String authType)  
            throws CertificateException {  
  
    }  
  
    @Override  
    public void checkServerTrusted(X509Certificate[] chain, String authType)  
            throws CertificateException {  
  
    }  
  
    @Override  
    public X509Certificate[] getAcceptedIssuers() {  
        return null;  
    }  
  
}

2、Page

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class Page {
   private int total; //总记录数
   private List<Map<String, Object>> list;
   private int pageNo; //当前页号
   private int pageSize;//一页记录数
   private int maxPageNo; //最大页数
   private List<Object> pageNoList = new ArrayList<>();
   
   public void setMaxPageNo(int maxPageNo) {
      this.maxPageNo = maxPageNo;
   }
   public void setPageNoList(List<Object> pageNoList) {
      this.pageNoList = pageNoList;
   }
   public int getMaxPageNo() {
      maxPageNo = total / pageSize;
      if(total % pageSize > 0 || total == 0){
         maxPageNo += 1; 
      }
      return maxPageNo;
   }
   public List<Object> getPageNoList(){
      getMaxPageNo();
      
      pageNoList = new ArrayList<Object>();
      if(pageNo <= 4 && maxPageNo <= pageNo+4){
         for(int i=1;i<=maxPageNo;i++){
            pageNoList.add(i);
         }
      }else if(pageNo <=4 && maxPageNo > pageNo+4){
         for(int i=1;i<=9;i++){
            pageNoList.add(i);
         }
      }else if(pageNo > 4 && maxPageNo <= pageNo+4 && pageNo != 5 && pageNo != 6 && pageNo != 7 && pageNo != 8){
         for(int i=maxPageNo-9;i<=maxPageNo;i++){
            pageNoList.add(i);
         }
      }else if(pageNo > 4 && maxPageNo > pageNo+4 ){
         for(int i=pageNo-4;i<=pageNo+4;i++){
            pageNoList.add(i);
         }
      }else {
         //处理5 5,6 6,7 7,8 8 (页码页数 最大页码)类型的数据
         for(int i=1;i<=maxPageNo;i++){
            pageNoList.add(i);
         }
      }
      
      //处理5 5,6 6,7 7,8 8 (页码页数 最大页码)类型的数据
      if (pageNoList.size()>0) {
         for(int i = 0; i < pageNoList.size();i++ ){
            if (Integer.valueOf(String.valueOf(pageNoList.get(i))) < 0) {
               pageNoList.remove(i);
            }
         }
      }
      
      return pageNoList;
   }
   public int getTotal() {
      return total;
   }
   public void setTotal(int total) {
      this.total = total;
   }
   public List<Map<String, Object>> getList() {
      return list;
   }
   public void setList(List<Map<String, Object>> list) {
      this.list = list;
   }
   public int getPageNo() {
      return pageNo;
   }
   public void setPageNo(int pageNo) {
      this.pageNo = pageNo;
   }
   public int getPageSize() {
      return pageSize;
   }
   public void setPageSize(int pageSize) {
      this.pageSize = pageSize;
   }

}

3、实现方法

url是路径,map是参数

public Page getRomoteSxt(String url, Map<String, Object> map) {

    Page page           = null;
    String resultString = null;
    try {
        resultString = HttpClientUtil.httpsRequest(url, HttpClientUtil.POST, map);
        JSONObject json = JSON.parseObject(resultString);
        if (json.getBoolean("success")) {
            page = json.getObject("data", Page.class);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    return page;
}

转载于:https://my.oschina.net/mdxlcj/blog/1859629

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Akka 远程调用的实现基于 Akka Remoting 模块。以下是一个简单的示例: 首先,需要在项目中添加 Akka Remoting 依赖: ```xml <dependency> <groupId>com.typesafe.akka</groupId> <artifactId>akka-remote_2.11</artifactId> <version>2.5.9</version> </dependency> ``` 然后,定义一个远程 Actor,它可以通过网络接收和处理消息: ```java import akka.actor.AbstractActor; import akka.event.Logging; import akka.event.LoggingAdapter; public class RemoteActor extends AbstractActor { private LoggingAdapter log = Logging.getLogger(getContext().getSystem(), this); @Override public Receive createReceive() { return receiveBuilder() .match(String.class, message -> { log.info("Received message: {}", message); getSender().tell("Hello from remote actor", getSelf()); }) .build(); } } ``` 接下来,在本地 Actor 中创建一个远程 Actor 的引用,并向其发送消息: ```java import akka.actor.ActorRef; import akka.actor.ActorSystem; import akka.actor.Props; import akka.pattern.Patterns; import scala.concurrent.Await; import scala.concurrent.duration.Duration; import java.util.concurrent.TimeUnit; public class LocalActor { public static void main(String[] args) throws Exception { ActorSystem system = ActorSystem.create("MySystem"); // 创建远程 Actor 的引用 ActorRef remoteActor = system.actorOf(Props.create(RemoteActor.class), "remoteActor"); // 向远程 Actor 发送消息,并等待其回复 String message = "Hello from local actor"; Object response = Patterns.ask(remoteActor, message, 5000).toCompletableFuture().get(5000, TimeUnit.MILLISECONDS); System.out.println("Received response: " + response); system.terminate(); } } ``` 在上面的代码中,我们使用 `Patterns.ask` 方法向远程 Actor 发送一条消息,并等待其回复。该方法返回一个 `Future` 对象,我们可以使用 `toCompletableFuture()` 方法将其转换为 Java 8 的 `CompletableFuture` 对象,从而方便地使用 `get` 方法等待结果。 以上就是一个简单的 Akka 远程调用的示例。在实际应用中,还需要配置 Akka Remoting 的一些参数,例如远程 Actor 的地址、端口等。具体配置方法可以参考 Akka 官方文档。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值