java模拟http/https post请求

简介: java模拟http/https post请求

1.Post请求失败的代码

try {
             HttpResponse response = httpClient.execute(httpPost);
             HttpEntity entity = response.getEntity();
             result = EntityUtils.toString(entity, "UTF-8");
             Util.log("API,POST回来的数据是:");
             Util.log(result);
         } catch (ConnectionPoolTimeoutException e) {
             log.e("http get throw ConnectionPoolTimeoutException(wait time out)");
         } catch (ConnectTimeoutException e) {
             log.e("http get throw ConnectTimeoutException");
         } catch (SocketTimeoutException e) {
             log.e("http get throw SocketTimeoutException");
         }  catch (Exception e) {
             log.e("http get throw Exception");
         } finally {
             httpPost.abort();
         }

之前每次代码执行到上述代码的第二行的时候,会等一段时间然后会捕获到Exception异常。

2.分析问题

当然捕获的Exception这个异常太大了我们不便于分析,我们查看一下httpClient.execute(HttpUriRequest uri)的方法;


a43a07ab0c7cfa23a5b0f52d724a9bf0.png

发下这个方法会抛出IOException, ClientProtocolException这两个异常,但是在调用方法的时候并没有明确捕获他们两个。

3.得出结论

所以很有可能在执行post请求的过程中,遇到了这两个问题,果然我们把代码完善之后

try {
            httpClient = new SSLClient();
            HttpResponse response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            result = EntityUtils.toString(entity, "UTF-8");
            Util.log("API,POST回来的数据是:");
            Util.log(result);
        } catch (ConnectionPoolTimeoutException e) {
            log.e("http get throw ConnectionPoolTimeoutException(wait time out)");
        } catch (ConnectTimeoutException e) {
            log.e("http get throw ConnectTimeoutException");
        } catch (SocketTimeoutException e) {
            log.e("http get throw SocketTimeoutException");
        } catch (ClientProtocolException e) {
            log.e("http get throw ClientProtocolException");
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            log.e("http get throw Exception");
        } finally {
            httpPost.abort();
        }

上述,完善完毕代码后捕捉到了IOException异常,我们把异常打印出来看到了如下信息。

80d994dd7151ba176ab11e1dc0c79b0b.png

4.解决问题

通过在网上查询可知,这是缺少安全证书时出现的异常,解决方案如下:

通过在网上查询可知,这是缺少安全证书时出现的异常,解决方案如下:


等待Oracle/Google/Mozilla等等组织信任CNNIC,算了,洗洗睡吧

使用Java的TrustManager忽略所有的SSL请求的证书,仅仅用于开发测试,限于篇幅不做介绍了

导入目标网站的证书,然后在开始调用之前,指定keystore就ok了,本文介绍下该方法

目前我们采用第二种方案:由于请求的URL是HTTPS的,为了避免需要证书,所以用一个类继承DefaultHttpClient类,忽略校验过程。


编写一个SSLClient类

package com.phicomm.smarthome.sharedwifi.util;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import org.apache.http.conn.ClientConnectionManager;
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.impl.client.DefaultHttpClient;
public class SSLClient extends DefaultHttpClient {
    public SSLClient() throws Exception {
        super();
        SSLContext ctx = SSLContext.getInstance("TLS");
        X509TrustManager tm = new X509TrustManager() {
            @Override
            public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                // TODO Auto-generated method stub
            }
            @Override
            public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                // TODO Auto-generated method stub
            }
            @Override
            public X509Certificate[] getAcceptedIssuers() {
                // TODO Auto-generated method stub
                return null;
            }
        };
        ctx.init(null, new TrustManager[] { tm }, null);
        SSLSocketFactory ssf = new SSLSocketFactory(ctx, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        ClientConnectionManager ccm = this.getConnectionManager();
        SchemeRegistry sr = ccm.getSchemeRegistry();
        sr.register(new Scheme("https", 443, ssf));
    }
}

对应的实现类:

public HttpResponse sendPostToService(String url, Object pushData) throws IOException, KeyStoreException,
            UnrecoverableKeyException, NoSuchAlgorithmException, KeyManagementException {
        if (!hasInit) {
            init();
        }
        String result = null;
        HttpPost httpPost = new HttpPost(url);
        StringEntity postEntity = new StringEntity(pushData.toString(),
                ContentType.create("application/x-www-form-urlencoded", "UTF-8"));
        // 设置一些Http头信息
        httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded");
        httpPost.addHeader("connection", "Keep-Alive");
        httpPost.addHeader("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
        // 将发送内容填装
        httpPost.setEntity(postEntity);
        // 设置请求器的配置
        httpPost.setConfig(requestConfig);
        // 打印待发送的数据
        Util.log("=====API,POST过去的数据是:");
        Util.log("executing request" + httpPost.getRequestLine());
        Util.log("请求头信息===" + httpPost.getAllHeaders().toString());
        Util.log("请求状态行===" + httpPost.getRequestLine());
        Util.log("请求配置===" + httpPost.getConfig());
        Util.log("请求实体===" + httpPost.getEntity().getContentEncoding() + httpPost.getEntity().getContentType()
                + httpPost.getEntity().getContent());
        HttpResponse response = null;
        try {
            // 忽略所有的SSL请求的证书
            httpClient = new SSLClient();
            response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            result = EntityUtils.toString(entity, "UTF-8");
            // 打印得到的响应信息
            Util.log("API,POST回来的数据是:");
            Util.log("=====Entity:" + result);
            Util.log("=====Headers:" + response.getAllHeaders());
            Util.log("=====StatusLine:" + response.getStatusLine());
            Util.log("=====Locale:" + response.getLocale());
        } catch (ConnectionPoolTimeoutException e) {
            log.e("http get throw ConnectionPoolTimeoutException(wait time out)");
        } catch (ConnectTimeoutException e) {
            log.e("http get throw ConnectTimeoutException");
        } catch (SocketTimeoutException e) {
            log.e("http get throw SocketTimeoutException");
        } catch (ClientProtocolException e) {
            log.e("http get throw ClientProtocolException");
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            log.e("http get throw Exception");
        } finally {
            httpPost.abort();
        }
        return response;
    }

在第36行使用自定义的SSLClient来忽略掉验证要求

另外注意在postMan中模拟调用的时候我们是用的x-www-form-urlencoded格式的数据请求,就是application/x-www-from-urlencoded,会将表单内的数据转换为键值对。

当action为get时候,浏览器用x-www-form-urlencoded的编码方式把form数据转换成一个字串(name1=value1&name2=value2...),然后把这个字串append到url后面,用?分割,加载这个新的url。 当action为post时候,浏览器把form数据封装到http body中,然后发送到server。


所以我们需要对传进来的数据做一下处理:

// 拼接x-www-form-urlencoded格式的请求参数
        String www_url = "coverimg=" + pushMsgModel.getCoverimg() + "&mode=" + pushMsgModel.getMode() + "&msgcontent="
                + pushMsgModel.getMsgContent() + "&msgtype=" + pushMsgModel.getMsgtype() + "&outline="
                + pushMsgModel.getOutline() + "&saveRecord=" + pushMsgModel.getSaveRecord() + "&source="
                + pushMsgModel.getSource() + "&ticker=" + pushMsgModel.getTicker() + "&timestamp="
                + pushMsgModel.getTimestamp() + "&title=" + pushMsgModel.getTitle() + "&uid=" + pushMsgModel.getUid()
                + "&url=" + pushMsgModel.getUrl();
        logger.info("x-www-form-urlencoded格式的请求参数为:" + www_url);

最后效果如下:


0e7bd215a1e53d7ea2db4d508c84f772.png

目录
相关文章
|
JSON 监控 API
掌握使用 requests 库发送各种 HTTP 请求和处理 API 响应
本课程全面讲解了使用 Python 的 requests 库进行 API 请求与响应处理,内容涵盖环境搭建、GET 与 POST 请求、参数传递、错误处理、请求头设置及实战项目开发。通过实例教学,学员可掌握基础到高级技巧,并完成天气查询应用等实际项目,适合初学者快速上手网络编程与 API 调用。
1402 130
|
设计模式 Java Spring
Java 设计模式之责任链模式:优雅处理请求的艺术
责任链模式通过构建处理者链,使请求沿链传递直至被处理,实现发送者与接收者的解耦。适用于审批流程、日志处理等多级处理场景,提升系统灵活性与可扩展性。
1469 2
|
XML JSON API
识别这些API接口定义(http,https,api,RPC,webservice,Restful api ,OpenAPI)
本内容介绍了API相关的术语分类,包括传输协议(HTTP/HTTPS)、接口风格(RESTful、WebService、RPC)及开放程度(API、OpenAPI),帮助理解各类API的特点与应用场景。
|
Android开发 Kotlin
HTTP协议中请求方式GET 与 POST 什么区别 ?
GET和POST的主要区别在于参数传递方式、安全性和应用场景。GET通过URL传递参数,长度受限且安全性较低,适合获取数据;而POST通过请求体传递参数,安全性更高,适合提交数据。
1046 2
|
JSON JavaScript API
Python模拟HTTP请求实现APP自动签到
Python模拟HTTP请求实现APP自动签到
|
数据采集 JSON Go
Go语言实战案例:实现HTTP客户端请求并解析响应
本文是 Go 网络与并发实战系列的第 2 篇,详细介绍如何使用 Go 构建 HTTP 客户端,涵盖请求发送、响应解析、错误处理、Header 与 Body 提取等流程,并通过实战代码演示如何并发请求多个 URL,适合希望掌握 Go 网络编程基础的开发者。
|
缓存 JavaScript 前端开发
Vue 3 HTTP请求封装导致响应结果无法在浏览器中获取,尽管实际请求已成功。
通过逐项检查和调试,最终可以定位问题所在,修复后便能正常在浏览器中获取响应结果。
536 0
|
Go
如何在Go语言的HTTP请求中设置使用代理服务器
当使用特定的代理时,在某些情况下可能需要认证信息,认证信息可以在代理URL中提供,格式通常是:
871 0
|
Web App开发 新零售 前端开发
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html><head><meta http-equiv="Cont
1.尽可能地了解需求,系统层面适用开闭原则 2.模块化,低耦合,能快速响应变化,也可以避免一个子系统的问题波及整个大系统 3.
1019 0

热门文章

最新文章