美文网首页
java中调用https接口 入参类型为String和form-

java中调用https接口 入参类型为String和form-

作者: 闲置的Programmer | 来源:发表于2019-06-25 19:33 被阅读0次

在java类中调用https接口,可以用下面的方法实现,只需要将接口url传入到该方法中,type是为了满足GET POST两个类型的需求
以下代码针对普通的参数请求,

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
public  String post(String path, String type) throws IOException, GeneralSecurityException {
        // 创建SSLContext对象,并使用我们指定的信任管理器初始化
        TrustManager[] tm = { new MyX509TrustManager() };
        SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
        sslContext.init(null, tm, new java.security.SecureRandom());
        // 从上述SSLContext对象中得到SSLSocketFactory对象
        javax.net.ssl.SSLSocketFactory ssf = sslContext.getSocketFactory();
        path.replaceAll("\r|\n","");

        URL url = new URL(path);
        HttpsURLConnection httpsConn = (HttpsURLConnection) url.openConnection();
        httpsConn.setSSLSocketFactory(ssf);
        //判断接口类型
        if(type!=null){
            httpsConn.setRequestMethod("GET");
        }else{
            httpsConn.setRequestMethod("POST");
        }
        httpsConn.setDoInput(true);// 打开输入流,以便从服务器获取数据
        httpsConn.setDoOutput(true);// 打开输出流,以便向服务器提交数据
        httpsConn.setRequestProperty("Content-Type", "application/json;charset=UTF-8");

        BufferedReader in = new BufferedReader(new InputStreamReader(httpsConn.getInputStream()));

        String line;
        StringBuffer rt = new StringBuffer();
        while ((line = in.readLine()) != null) {
            rt.append(line);
        }
        return rt.toString();
    }

在调用接口时,涉及到文件类型的参数就比较麻烦,不过问题总有解决的方法,以下代码能做到在请求https接口时入参类型为form-data的图片和String型的参数

相关的pom文件

        <dependency>
            <groupId>org.wso2.apache.httpcomponents</groupId>
            <artifactId>httpmime</artifactId>
            <version>4.3.1.wso2v1</version>
        </dependency>

                <dependency>
            <groupId>org.wso2.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.3.1.wso2v1</version>
        </dependency>

工具类代码


import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.params.ConnManagerParams;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.File;
import java.net.URI;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Map;

/**
 * Created with pengyouqi
 * 2019/6/26 11:27
 * 调用外部https接口
 */

public class HttpsProtocolUtil {


    public static String doHttpPost(String url,String image)
    {
        try
        {
            HttpClient httpsClient = getHttpsClient();

            HttpPost request = new HttpPost();
            request.setURI(URI.create(url));

            MultipartEntity muit = new MultipartEntity();
            File file = new File(image);
            FileBody fileBody = new FileBody(file);
            //图片类型
            muit.addPart("image",fileBody);
            //String类型
            muit.addPart("encoding",new StringBody("base64"));
            //json类型
            muit.addPart("params",new StringBody("{\"color_level\":5,\"origin\":\"bailiang1\",\"eye_enlarging\":0,\"cheek_thinning\":0,\"red_level\":0}"));
            request.setEntity(muit);

            // 发送请求
            HttpResponse httpResponse = httpsClient.execute(request);
            // 得到应答的字符串
            String retSrc = EntityUtils.toString(httpResponse.getEntity());
            return retSrc;
        }
        catch (Exception e)
        {
            // log.error("", e);
        }
        return null;
    }




    @SuppressWarnings("deprecation")
    private static HttpClient getHttpsClient()
            throws Exception
    {
        HttpParams httpParams = new BasicHttpParams();
        // 版本
        HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1);
        // 编码
        HttpProtocolParams.setContentCharset(httpParams, HTTP.UTF_8);
        HttpProtocolParams.setUseExpectContinue(httpParams, true);
        // 最大连接数
        ConnManagerParams.setMaxTotalConnections(httpParams, 1000);
        // 超时
        HttpConnectionParams.setConnectionTimeout(httpParams, 1000 * 60 * 3);
        HttpConnectionParams.setSoTimeout(httpParams, 1000 * 60 * 3);

        SSLContext ctx = SSLContext.getInstance("TLS");
        X509TrustManager tm = new X509TrustManager()
        {
            public X509Certificate[] getAcceptedIssuers()
            {
                return null;
            }

            public void checkClientTrusted(X509Certificate[] arg0, String arg1)
                    throws CertificateException
            {}

            public void checkServerTrusted(X509Certificate[] arg0, String arg1)
                    throws CertificateException
            {}
        };
        ctx.init(null, new TrustManager[] {tm}, null);
        SSLSocketFactory ssf = new SSLSocketFactory(ctx,
                SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        SchemeRegistry registry = new SchemeRegistry();
        registry.register(new Scheme("https", 443, ssf));
        ThreadSafeClientConnManager mgr = new ThreadSafeClientConnManager(registry);
        HttpClient httpsClient = new DefaultHttpClient(mgr, httpParams);
        return httpsClient;
    }
}

相关文章

网友评论

      本文标题:java中调用https接口 入参类型为String和form-

      本文链接:https://www.haomeiwen.com/subject/xanxcctx.html