0


java 模拟postman的 x-www-form-urlencoded 方式访问

1 jar 包引入:

<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpcore</artifactId>
    <version>4.4.5</version>
</dependency>
<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.7</version>
</dependency>

2 写访问方法

代码:

public static String upLoadCert(String postURL,String ssl){
    DefaultHttpClient client = new DefaultHttpClient();
    String  resut="{\"code\":401,\"message\":\"开始调用\"}";
    try {
        HttpPost postMethod=new HttpPost(postURL);//设置头信息
        postMethod.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
        postMethod.setHeader("Authorization", "认证信息");
        postMethod.setHeader("Date", DateUtil.format(new Date(), DateUtil.DATEFORMATSECOND));
        List<BasicNameValuePair> list=new ArrayList<>();
        list.add(new BasicNameValuePair("ssl",ssl));
        postMethod.setEntity(new UrlEncodedFormEntity(list,"UTF-8"));
        HttpResponse response=client.execute(postMethod);//返回结果
        System.out.println(response.getStatusLine().getStatusCode());
        HttpEntity entity=response.getEntity();
        if (entity != null) {
            resut = EntityUtils.toString(entity,"UTF-8");
            System.out.println(resut);
            EntityUtils.consume(entity);
            return resut;
        }
    } catch(Exception e){
        e.printStackTrace();
    }finally{
        client.getConnectionManager().shutdown();
        return resut;
    }
}

本文转载自: https://blog.csdn.net/weixin_37855495/article/details/124950148
版权归原作者 元永真 所有, 如有侵权,请联系我们删除。

“java 模拟postman的 x-www-form-urlencoded 方式访问”的评论:

还没有评论