httpclient模拟post(applecation/x-www-form-urlencoded方式)请求

Posted h-dream

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了httpclient模拟post(applecation/x-www-form-urlencoded方式)请求相关的知识,希望对你有一定的参考价值。

http post请求工具类:

/**
     * 非json参数方式POST提交
     *
     * @param url
     * @param params
     * @return
     */
    public static String httpPost(String uri, List<NameValuePair> params) {
        String result = "";
        try {
            CloseableHttpClient httpclient = HttpClients.createDefault();
            HttpPost httpPost = new HttpPost(uri);
            httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded"); // 添加请求头
            httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
            System.out.println(httpPost);
            HttpResponse response = httpclient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                InputStream instreams = entity.getContent();
                result = convertStreamToString(instreams);
                System.out.println(result);
            }
        } catch (Exception e) {
            e.getMessage();
        }
        return result;
    }


    public static String convertStreamToString(InputStream is) {
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();

        String line = null;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line + "
");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return sb.toString();
    }

请求数据组装:

  public R authenticationInfo(AuthenticationInfoEntity authenticationInfo) {


        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair("apiCode", "P203"));
        nvps.add(new BasicNameValuePair("account", "demo"));
        nvps.add(new BasicNameValuePair("password", "UGFpbGllQDIwMTk="));
        nvps.add(new BasicNameValuePair("name", authenticationInfo.getAiFullName()));
        nvps.add(new BasicNameValuePair("cid", authenticationInfo.getAiIdCard()));
        nvps.add(new BasicNameValuePair("bankCard", authenticationInfo.getAiBankAccount()));
        nvps.add(new BasicNameValuePair("mobile", authenticationInfo.getAiMobile()));

        String jsonStr = httpPost(uri, nvps); //post请求
}

 

以上是关于httpclient模拟post(applecation/x-www-form-urlencoded方式)请求的主要内容,如果未能解决你的问题,请参考以下文章

Java模拟POST表单提交HttpClient操作

httpclient模拟post请求json封装表单数据

C#用httpclient模拟post到web网站上

httpclient模拟post请求json封装表单数据

用HttpClient的post模拟搜索结果只有正常结果的一部分

如何使用HttpClient模拟浏览器GET POST