• 后端请求第三方接口,并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
    我不是来改变世界的
  • 相关阅读:
    译:编程面试的10大算法概念汇总
    Android内存优化之封装九宫格
    Android Java 程序员必备开发工具
    译:如何成为一个通晓多种编程语言的程序员
    8大排序算法图文讲解
    Android酷炫实用的开源框架(UI框架)
    Android动态加载字节码
    利用无效字节码指令引发逆向工具崩溃(二)
    oracle 12c linux服务器启动监听
    oracle无主键去重方法
  • 原文地址:https://www.cnblogs.com/notchangeworld/p/11232659.html
Copyright © 2020-2023  润新知