Java实现post请求

Posted 皓洲

tags:

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

post请求返回实体类

public static <T> T httpPost(String url, Map<String, String> header, Object parameter, Class<T> t, Integer timeOut) 
        String rtnStr = postImpl(url, header, parameter, timeOut, ContentType.APPLICATION_JSON);
        if (CommonUtil.isNull(rtnStr)) 
            return null;
         else if (t.getName().equals("java.lang.String")) 
            return rtnStr;
         else 
            T returnObj = null;
            returnObj = JsonUtil.fromJson(rtnStr, t);
            return returnObj;
        
    

    private static String postImpl(String url, Map<String, String> header, Object parameter, Integer timeOut, ContentType type) 
        long startTime = System.currentTimeMillis();
        String body = null;
        String parameterJson = JsonUtil.allToJson(parameter);
        if (CommonUtil.isNotNull(parameterJson) && parameterJson.length() > 600) 
            logger.info("开始执行http post调用,url为: [" + url + "]  参数太多,展示前500个字符 内容为: [  " + parameterJson.substring(0, 500) + "  ]\\n\\n");
         else 
            logger.info("开始执行http post调用,url为: [" + url + "]  参数: [  " + parameterJson + "  ] \\n\\n");
        

        HttpClient httpclient = null;

        try 
            httpclient = wrapClient(url, timeOut);
            HttpPost post = new HttpPost(url);
            if (CommonUtil.isNull(header)) 
                setHeader(post);
             else 
                Iterator var11 = header.keySet().iterator();

                while(var11.hasNext()) 
                    String key = (String)var11.next();
                    post.addHeader(key, (String)header.get(key));
                
            

            if (parameter.getClass().equals(String.class)) 
                post.setEntity(new StringEntity((String)parameter, type));
             else 
                post.setEntity(new StringEntity(parameterJson, type));
            

            HttpResponse response = httpclient.execute(post);
            long endTime = System.currentTimeMillis();
            logger.info("调用API 花费时间(单位:毫秒):" + (endTime - startTime));
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode != 200) 
                logger.error("POST 请求调用失败:" + response.getStatusLine());
             else 
                body = EntityUtils.toString(response.getEntity(), Consts.UTF_8);
                if (CommonUtil.isNotNull(body) && body.length() > 1000) 
                    logger.info("POST 请求调用成功,报文太长,展示前500个字符,报文为:" + body.substring(0, 500));
                 else 
                    logger.info("POST 请求调用成功,获取到的报文为:" + body);
                
            
         catch (UnsupportedEncodingException var15) 
            logger.error(CommonUtil.getExceptionMessage(var15));
         catch (ClientProtocolException var16) 
            logger.error(CommonUtil.getExceptionMessage(var16));
         catch (IOException var17) 
            logger.error(CommonUtil.getExceptionMessage(var17));
        

        return body;
    

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请求