java基础的http请求工具类

RestTemplate请求

在springboot中使用方便

/**
 * application/x-www-form-urlencoded请求
 */
public static String postWithParams(){
    MultiValueMap<String, Object> postParameters = new LinkedMultiValueMap<>();
    postParameters.add("param1","value1");
    HttpEntity<MultiValueMap<String, Object>> entity = new HttpEntity<>(postParameters);
    RestTemplate restTemplate=new RestTemplate();
    return restTemplate.postForObject("http://xxx/api.htm", entity, String.class);
}

/**
 * application/json、application/xml等
 */
public static String postWithBody(){
    String body="{}";
    HttpEntity<String> entity = new HttpEntity<>(body,getHeaders());//header选填
    RestTemplate restTemplate=new RestTemplate();
    return restTemplate.postForObject("http://xxx/api.htm", entity, String.class);
}

private static HttpHeaders getHeaders() {
    HttpHeaders headers = new HttpHeaders();
    MediaType type = MediaType.parseMediaType("text/xml;charset=GBK");
    headers.setContentType(type);
    headers.add("token","111");
    return headers;
}

hutool工具类

需要hutool包

HttpResponse res=HttpRequest.post("http://xxx")
        .header("Authorization","aaaaaaaaaaaa")
        .form("kk","vv")
        .body("{}")
        .execute();

httpclient请求

以前很常用

HttpClient httpClient= HttpClientBuilder.create().build();
HttpPost httpPost = new HttpPost(url);
RequestConfig requestConfig= RequestConfig.custom().setConnectTimeout(10000).setSocketTimeout(4 * 60 * 1000).build();
httpPost.setConfig(requestConfig);
// 创建参数队列:application/x-www-form-urlencoded请求
List<NameValuePair> nameValuePairList = new ArrayList<>();
nameValuePairList.add(new BasicNameValuePair("key1", req));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairList, "utf-8"));

// 创建请求体:application/json、application/xml等
//httpPost.setHeader("Content-Type","application/json");
//String content="{}";
//HttpEntity httpEntity=new StringEntity(content,"utf-8");
//httpPost.setEntity(httpEntity);

HttpResponse response=httpClient.execute(httpPost);
HttpEntity re = response.getEntity();
if (response.getStatusLine().getStatusCode() == 200) {
    return EntityUtils.toString(response.getEntity(), "utf-8");
}

HttpURLConnection请求

使用较少

public static String doPostXml(String XML, String url){
    HttpURLConnection conn =null;
    OutputStreamWriter out = null;
    BufferedReader in = null;
    StringBuilder result = new StringBuilder();
    try {
    URL realUrl = new URL(url);
    // 打开和URL之间的连接
    conn = (HttpURLConnection) realUrl.openConnection();
    // 设置通用的请求属性
    conn.setRequestProperty("accept", "*/*");
    conn.setRequestProperty("connection", "Keep-Alive");
    conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
    conn.setRequestProperty("Content-Type", "text/xml; charset=utf-8");
    conn.setRequestProperty("SOAPAction", "http://xxx");
    conn.setDoOutput(true);
    conn.setDoInput(true);
    conn.setConnectTimeout(20000);
    conn.setReadTimeout(20000);
    conn.setRequestMethod("POST");
    out = new OutputStreamWriter(conn.getOutputStream(), StandardCharsets.UTF_8);
    out.write(XML);
    out.flush();
    int code = conn.getResponseCode();
    if (code == 200) {
        in = new BufferedReader(new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8));
    } else {
        log.error("doPostXml response error code ==>"+code);
        in = new BufferedReader(new InputStreamReader(conn.getErrorStream(), StandardCharsets.UTF_8));
    }
    String line;
    while ((line = in.readLine()) != null) {
        result.append(line);
    }
    return result.toString();
}

https请求

方式1:设置SSL创建httpclient

SSLConnectionSocketFactory socketFactory=new SSLConnectionSocketFactory(
        SSLContexts.custom().loadTrustMaterial(null,new TrustSelfSignedStrategy()).build(),
        NoopHostnameVerifier.INSTANCE
);
HttpClient httpClient= HttpClients.custom().setSSLSocketFactory(socketFactory).build();
HttpPost httpPost=new HttpPost(url);
//后续省略

方式2:请求类添加static模块,然后正常请求
需要配合适用下面生成的证书

static{
    javax.net.ssl.HttpsURLConnection.setDefaultHostnameVerifier(
            (hostname, sslSession) -> {
                //请求的域名或ip地址
                return hostname.equals("platform.xxx.com");
            });
    //第二个参数为证书的路径
    System.setProperty("javax.net.ssl.trustStore", "D:\\360\\jssecacerts");
    System.setProperty("javax.net.ssl.trustStorePassword", "changeit");
}

生成证书的方式

private static void getCert() throws Exception{
    String host = "xxx";
    int port =8888;
    char[] passphrase;
    String p = "changeit";
    passphrase = p.toCharArray();

    File file = new File("jssecacerts");
    if (!file.isFile()) {
        char SEP = File.separatorChar;
        File dir = new File(System.getProperty("java.home") + SEP + "lib" + SEP + "security");
        file = new File(dir, "jssecacerts");
        if (!file.isFile()) {
            file = new File(dir, "cacerts");
        }
    }
    System.out.println("Loading KeyStore " + file + "...");
    InputStream in = new FileInputStream(file);
    KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
    ks.load(in, passphrase);
    in.close();

    SSLContext context = SSLContext.getInstance("TLS");
    TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    tmf.init(ks);
    X509TrustManager defaultTrustManager = (X509TrustManager)tmf.getTrustManagers()[0];
    SavingTrustManager tm = new SavingTrustManager(defaultTrustManager);
    context.init(null, new TrustManager[] {tm}, null);
    SSLSocketFactory factory = context.getSocketFactory();

    System.out.println("Opening connection to " + host + ":" + port + "...");
    SSLSocket socket = (SSLSocket)factory.createSocket(host, port);
    socket.setSoTimeout(10000);
    try {
        System.out.println("Starting SSL handshake...");
        socket.startHandshake();
        socket.close();
        System.out.println();
        System.out.println("No errors, certificate is already trusted");
    } catch (SSLException e) {
        System.out.println();
        e.printStackTrace(System.out);
    }

    X509Certificate[] chain = tm.chain;
    if (chain == null) {
        System.out.println("Could not obtain server certificate chain");
        return;
    }

    BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));

    System.out.println();
    System.out.println("Server sent " + chain.length + " certificate(s):");
    System.out.println();

    MessageDigest sha1 = MessageDigest.getInstance("SHA1");
    MessageDigest md5 = MessageDigest.getInstance("MD5");
    for (int i = 0; i < chain.length; i++) {
        X509Certificate cert = chain[i];
        System.out.println(" " + (i + 1) + " Subject " + cert.getSubjectDN());
        System.out.println("   Issuer  " + cert.getIssuerDN());
        sha1.update(cert.getEncoded());
        System.out.println("   sha1    " + toHexString(sha1.digest()));
        md5.update(cert.getEncoded());
        System.out.println("   md5     " + toHexString(md5.digest()));
        System.out.println();
    }

    System.out.println("Enter certificate to add to trusted keystore or 'q' to quit: [1]");
    String line = reader.readLine().trim();
    int k;
    try {
        k = (line.length() == 0) ? 0 : Integer.parseInt(line) - 1;
    } catch (NumberFormatException e) {
        System.out.println("KeyStore not changed");
        return;
    }

    X509Certificate cert = chain[k];
    String alias = host + "-" + (k + 1);
    ks.setCertificateEntry(alias, cert);

    OutputStream out = new FileOutputStream("jssecacerts");
    ks.store(out, passphrase);
    out.close();

    System.out.println();
    System.out.println(cert);
    System.out.println();
    System.out.println("Added certificate to keystore 'jssecacerts' using alias '" + alias + "'");
}

webservice接口call方法调用

适用webservice接口一般http请求不成功的情况

private static String post(JSONObject param) throws Exception{
    // 指出service所在完整的URL
    String targetNamespace = "http://www.xxx.com.cn";
    //所调用接口的方法method
    String method="GetBrowserCatalog";
    // 指出service所在完整的URL
    String webserviceUrl = "http://xxx?Handler=GenPatientEMRWSDL";
    Service service=new Service();
    Call call= (Call) service.createCall();
    call.setTargetEndpointAddress(new URL(webserviceUrl));
    call.setOperationName(new QName(targetNamespace, method));
    call.setUseSOAPAction(true);

    //拼接参数
    String[] values=new String[param.size()];
    int i=0;
    for (Object s:param.keySet()){
        //设置参数名 第二个参数表示String类型,第三个参数表示入参;每个参数add一次
        call.addParameter(new QName(targetNamespace, s.toString()),Constants.XSD_STRING,ParameterMode.IN);
        values[i]=param.getString(s.toString());
        i++;
    }
    // 设置返回类型
    call.setReturnType(Constants.XSD_STRING);
    return (String) call.invoke(values);
}

依赖

<dependency>
	<groupId>org.apache.axisgroupId>
	<artifactId>axisartifactId>
	<version>1.4version>
dependency>
<dependency>
	<groupId>javax.xml.rpcgroupId>
	<artifactId>javax.xml.rpc-apiartifactId>
	<version>1.1.1version>
dependency>

原文注意事项:
请确认.NET的WebService类(即.asmx文件下的类)是否有[SoapDocumentService(RoutingStyle=SoapServiceRoutingStyle.RequestElement)]属性值,没有需要添加

你可能感兴趣的:(工具类,java,http)