Java实现post请求

Posted 皓洲

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java实现post请求相关的知识,希望对你有一定的参考价值。

public String postData(String url, Map<String, Object> params) throws Exception 
        //创建post请求对象
        HttpPost httppost = new HttpPost(url);
        // 获取到httpclient客户端
        CloseableHttpClient httpclient = HttpClients.createDefault();
        try 
            //创建参数集合
            List<BasicNameValuePair> list = new ArrayList<BasicNameValuePair>();
            //添加请求头参数
//                    if(url.equals(GetOlapDataUrl)) 
//                          httppost.addHeader("Content-Type", "application/json");
//                          httppost.addHeader("accessToken",params.get("accessToken").toString());
//                      
            // 设置请求的一些配置设置,主要设置请求超时,连接超时等参数
            RequestConfig requestConfig = RequestConfig.custom()
                    .setConnectTimeout(200000).setConnectionRequestTimeout(200000).setSocketTimeout(200000)
                    .build();
            httppost.setConfig(requestConfig);
            /**
             生产Cookie
             **/
            httppost.setHeader("Cookie","xxxxxx");
            //添加参数
            httppost.setEntity(new StringEntity(JSONObject.toJSONString(params), ContentType.create("application/json", "utf-8")));
            // 请求结果
            String resultString = "";
            //启动执行请求,并获得返回值
            CloseableHttpResponse response = httpclient.execute(httppost);
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) 
                // 获取请求响应结果
                HttpEntity entity = response.getEntity();
                if (entity != null) 
                    // 将响应内容转换为指定编码的字符串
                    resultString = EntityUtils.toString(entity, "UTF-8");
                    System.out.printf("Response content:", resultString);
                    return resultString;
                
             else 
                System.out.println("请求失败!");
                return resultString;
            
         catch (Exception e) 
            throw e;
         finally 
            httpclient.close();
        
        return null;
    

以上是关于Java实现post请求的主要内容,如果未能解决你的问题,请参考以下文章

Java实现post请求

Java实现post请求

java实现post请求(PostMethod)

Java使用HttpClient实现Post请求

Java使用HttpClient实现Post请求

Java实现post和get请求