zoukankan      html  css  js  c++  java
  • 后端请求第三方接口,并json形式传输数据

    private String getToken(String name, String newPw, String ip) {
    Map<String,String> map = new HashMap<>();

    String url = "要访问的接口";

    String jsonStr = "{"user":""+name+"","password":""+newPw+""}";

    RequestConfig config = RequestConfig.custom().setSocketTimeout(40000).setConnectTimeout(40000).setConnectTimeout(40000).build();
    HttpClient httpClient;
    httpClient = createCloseableHttpClient(url,config);
    HttpUriRequest httpMethod = null;
    HttpPost pMethod = new HttpPost(url);
    pMethod.setConfig(config);


    try {
    //进行json的转换
    pMethod.addHeader("Content-Type","application/json;charset=utf-8");
    // String s = jsonObject.toString();
    StringEntity entity = new StringEntity(jsonStr,ContentType.APPLICATION_JSON);
    pMethod.setEntity(entity);


    httpMethod = pMethod;
    HttpResponse resp = httpClient.execute(httpMethod);
    Integer statusCode = resp.getStatusLine().getStatusCode();
    String respContent = IOUtils.toString(resp.getEntity().getContent(),"utf-8");
    respContent = respContent==null?"":respContent;

    System.out.println(respContent);
    System.out.println(statusCode.toString());
    Gson gson = new Gson();
    map = gson.fromJson(respContent,map.getClass());

    System.out.println("token value "+map.get("token"));


    } catch (Exception e) {
    e.printStackTrace();
    }
    return map.get("token");
    }

    /**
    * 忽略证书的方法
    * @param url
    * @param config
    * @return
    */
    private static HttpClient createCloseableHttpClient(String url, RequestConfig config) {
    HttpClientBuilder builder = HttpClients.custom();
    builder.setDefaultRequestConfig(config);
    if(url.startsWith("https")){
    try {
    SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
    @Override
    public boolean isTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
    return true;
    }
    }).build();

    SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext,SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

    builder.setSSLSocketFactory(sslsf);

    } catch (NoSuchAlgorithmException e) {
    e.printStackTrace();
    } catch (KeyManagementException e) {
    e.printStackTrace();
    } catch (KeyStoreException e) {
    e.printStackTrace();
    }

    }
    return builder.build();
    }

    有问题可加微信联系:chanhle0109
    我不是来改变世界的
  • 相关阅读:
    4.3 DDL 数据类型
    Log4j的简要概述
    Eclipse/IDEA使用小技巧
    idea-生成key的Java代码
    Java8新特性--lamada详解
    JQuery基本语法
    EL与Velocity基本语法总结:
    RAF(RandomAccessFile)类
    Java篇-File类之常用操作
    Java篇-File类之创建删除
  • 原文地址:https://www.cnblogs.com/notchangeworld/p/11232659.html
Copyright © 2011-2022 走看看