热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

httpclient之发送字符串

publicStringHttpPostWithJson(Stringurl,Stringjson){StringreturnValue这是默认返回值,接
public String HttpPostWithJson(String url, String json) {
        String returnValue = "这是默认返回值,接口调用失败";
        CloseableHttpClient httpClient = HttpClients.createDefault();
        ResponseHandler respOnseHandler= new BasicResponseHandler();
        try{
            //第一步:创建HttpClient对象
         httpClient = HttpClients.createDefault();
             
             //第二步:创建httpPost对象
            HttpPost httpPost = new HttpPost(url);
            
            //第三步:给httpPost设置JSON格式的参数
            StringEntity requestEntity = new StringEntity(json,"utf-8");
            requestEntity.setContentEncoding("UTF-8");                
            httpPost.setHeader("Content-type", "application/json");
            httpPost.setEntity(requestEntity);
           
           //第四步:发送HttpPost请求,获取返回值
           returnValue = httpClient.execute(httpPost,responseHandler); //调接口获取返回值时,必须用此方法
//           CloseableHttpResponse httpResOnse= httpClient.execute(httpPost);
//           int statusCode = httpResonse.getStatusLine().getStatusCode();
//           if(statusCode!=200)
//           {
//                System.out.println("请求发送失败,失败的返回参数为:"+httpResonse.getStatusLine());
//                returnValue = httpResonse.getStatusLine().toString();      
//           }
//           
          
        }
         catch(Exception e)
        {
             e.printStackTrace();
        }
        
        finally {
           try {
            httpClient.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        }
         //第五步:处理返回值
         return returnValue;
    }

 


推荐阅读
author-avatar
卟抛棄D
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有