• HttpClient和Gson跨域访问


    httpClient下载地址

    Gson下载地址


    客户端:

    import java.io.IOException;
    import java.io.UnsupportedEncodingException;
    import java.net.URLDecoder;
    import java.security.KeyManagementException;
    import java.security.NoSuchAlgorithmException;
    import java.security.cert.CertificateException;
    import java.security.cert.X509Certificate;
    import java.util.HashMap;
    import java.util.Map;
    import javax.net.ssl.SSLContext;
    import javax.net.ssl.TrustManager;
    import javax.net.ssl.X509TrustManager;
    import org.apache.http.HttpEntity;
    import org.apache.http.HttpResponse;
    import org.apache.http.HttpStatus;
    import org.apache.http.StatusLine;
    import org.apache.http.client.ClientProtocolException;
    import org.apache.http.client.HttpClient;
    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.conn.ssl.SSLConnectionSocketFactory;
    import org.apache.http.entity.StringEntity;
    import org.apache.http.impl.client.CloseableHttpClient;
    import org.apache.http.impl.client.DefaultHttpClient;
    import org.apache.http.impl.client.HttpClients;
    import org.apache.http.util.EntityUtils;
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    
    
    /**
     * 封装http用于跨域请求
     * 
     * @author Bai
     * 
     */
    public class HttpUtil {
    
        private static Logger logger = LoggerFactory.getLogger(HttpUtil.class);
    
        /**
         * get请求
         * 
         * @return
         */
        public static String doGet(String url) {
            try {
                HttpClient client = new DefaultHttpClient();
                // 发送get请求
                HttpGet request = new HttpGet(url);
                HttpResponse response = client.execute(request);
                /** 请求发送成功,并得到响应 **/
                if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                    /** 读取服务器返回过来的json字符串数据 **/
                    String strResult = EntityUtils.toString(response.getEntity());
                    return strResult;
                }
            } catch (IOException e) {
                logger.error("doPost请求提交失败:" + url, e);
            }
    
            return null;
        }
    
        /**
         * post请求(用于请求json格式的参数)
         * 
         * @param url
         * @param params
         * @return
         */
        public static String doPost(String url, String params) throws Exception {
            CloseableHttpClient httpclient = HttpClients.createDefault();
            HttpPost httpPost = new HttpPost(url);// 创建httpPost
            httpPost.setHeader("Accept", "application/json");
            httpPost.setHeader("Content-Type", "application/json");
            String charSet = "UTF-8";
            StringEntity entity = new StringEntity(params, charSet);
            httpPost.setEntity(entity);
            CloseableHttpResponse response = null;
            try {
                response = httpclient.execute(httpPost);
                StatusLine status = response.getStatusLine();
                int state = status.getStatusCode();
                if (state == HttpStatus.SC_OK) {
                    HttpEntity responseEntity = response.getEntity();
                    String jsonString = EntityUtils.toString(responseEntity);
                    return jsonString;
                }
            }catch(Exception e){
                logger.error("doPost请求提交失败:" + url, e);
            }finally {
                if (response != null) {
                    try {
                        response.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                try {
                    httpclient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return null;
        }
    
        /**
         * httpPost
         * @param url  路径
         * @param strargs 参数
         * @return
         */
        public static String sendRequest(String url, Object strargs) {
            return httpPost(url, strargs.toString(), false);
        }
        /**
         * post请求
         * @param url         url地址
         * @param strargs     参数
         * @param noNeedResponse    不需要返回结果
         * @return
         */
        public static String httpPost(String url,String strargs, boolean noNeedResponse){
            //post请求返回结果
            String str = "";
            try {
                SSLContext ssl = SSLContext.getInstance("TLS");
                X509TrustManager trustManager=new X509TrustManager() {
                    @Override
                    public X509Certificate[] getAcceptedIssuers() {
                        return null;
                    }
                    @Override
                    public void checkServerTrusted(X509Certificate[] chain, String authType)
                            throws CertificateException {
                    }
                    
                    @Override
                    public void checkClientTrusted(X509Certificate[] chain, String authType)
                            throws CertificateException {
                    }
                };
                ssl.init(null, new TrustManager[]{trustManager}, null);
                SSLConnectionSocketFactory ssf = new SSLConnectionSocketFactory(ssl,SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); 
                CloseableHttpClient httpClient =  HttpClients.custom().setSSLSocketFactory(ssf) .build();
                HttpPost httpost = new HttpPost(url);
                 if (null != strargs && !strargs.equals("")) {
                        //解决中文乱码问题
                        StringEntity entity = new StringEntity(strargs, "utf-8");
                        entity.setContentEncoding("UTF-8");
                        entity.setContentType("application/json");
                        httpost.setEntity(entity);
                    }
                    HttpResponse result = httpClient.execute(httpost);
                    url = URLDecoder.decode(url, "UTF-8");
                    /**请求发送成功,并得到响应**/
                    if (result.getStatusLine().getStatusCode() == 200) {
                        try {
                            /**读取服务器返回过来的json字符串数据**/
                            str = EntityUtils.toString(result.getEntity());
                            if (noNeedResponse) {
                                return null;
                            }
                        } catch (Exception e) {
                            logger.error("httpPost请求提交失败:" + url, e);
                        }
                    }
            } catch (NoSuchAlgorithmException e1) {
                e1.printStackTrace();
            } catch (KeyManagementException e) {
                e.printStackTrace();
            } catch (UnsupportedEncodingException e1) {
                e1.printStackTrace();
            } catch (ClientProtocolException e1) {
                e1.printStackTrace();
            } catch (IOException e) {
                logger.error("httpPost请求提交失败:" + url, e);
            }
            return str;
        }
        public static void main(String[] args) throws Exception {
            Map<String, String> map = new HashMap<String, String>();
            map.put("1", "1");
            map.put("2", "2");
    //        String doGet = HttpUtil.doPost("http://192.168.3.14:8080/test1/servlet/Test",map.toString());
    //        System.out.println(doGet);
            String sendRequest = HttpUtil.sendRequest("http://192.168.3.14:8080/test1/servlet/Test", map);
            System.out.println(sendRequest);
        }
    }

    服务端:

    import java.io.ByteArrayOutputStream;
    import java.io.IOException;
    import java.io.PrintWriter;
    import java.util.Map;
    
    import javax.servlet.ServletException;
    import javax.servlet.ServletInputStream;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    
    import com.google.gson.Gson;
    import com.google.gson.reflect.TypeToken;
    
    public class Test extends HttpServlet {
        /**
         * 服务端
         */
        public void doGet(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            doPost(request, response);
            
        }
    
    
        public void doPost(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            //处理数据,可以判断长度保证数据不为空
            if(request.getContentLength() > 0){
                Map<String, String> callResultMap = getCallResultMap(request);
                for(Map.Entry<String, String> entry : callResultMap.entrySet()){
                    System.out.println(entry.getKey()+"---"+entry.getValue());
                }
            }
            //处理逻辑
            
            //返回给调用者json数据
            response.setContentType("text/html;charset=utf-8");
            PrintWriter writer = response.getWriter();
            writer.print(new Gson().toJson("返回数据"));
        }
        
        /**
         * 传输过来的数据进行转换
         * @param request
         * @return
         * @throws IOException
         */
        public Map<String, String> getCallResultMap(HttpServletRequest request) throws IOException{
            ServletInputStream inputStream = request.getInputStream();
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();//字节数组输出流
            byte[] buffer = new byte[1024];
            int len = 0;
            while((len = inputStream.read(buffer)) != -1){
                outputStream.write(buffer, 0, len);
            }
            outputStream.close();
            inputStream.close();
            //转换成String,并编译UTF-8格式
            String str = new String(outputStream.toByteArray(),"UTF-8");
            //转换json数据为java对象,如果使用复合数据如:list,map等需要用TypeToken来实现
            Gson gson = new Gson();
            Map<String, String> resulMap = gson.fromJson(str, new TypeToken<Map<String, String>>() {}.getType());
            return resulMap;
        }
        
        
    }
  • 相关阅读:
    sunjiali
    dingding
    xlrd
    Python基础2
    Python常用算法学习
    Python基础1
    分布式监控系统
    堡垒机
    通过Python实现简单的计算器
    Python常用模块学习
  • 原文地址:https://www.cnblogs.com/cypress/p/8671684.html
Copyright © 2020-2023  润新知