httpclient 封装 http(get put post delete)请求

@SuppressWarnings("deprecation")
public class HttpClientUtil {
    private static Logger logger = LoggerFactory.getLogger(HttpClientUtil.class);
    private static final String ContentEncoding = "UTF-8";
    private static final int SocketTimeout = 5000;

    /**
     httpClient的get请求方式
     * @return
     * @throws Exception
     */
    public static String doGet(String url)   {
        logger.info("get请求{}",url);
      /*
       * 使用 GetMethod 来访问一个 URL 对应的网页,实现步骤:
       * 1:生成一个 HttpClinet 对象并设置相应的参数。
       * 2:生成一个 GetMethod 对象并设置响应的参数。
       * 3:用 HttpClinet 生成的对象来执行 GetMethod 生成的Get方法。
       * 4:处理响应状态码。
       * 5:若响应正常,处理 HTTP 响应内容。
       * 6:释放连接。
       */
      /* 1 生成 HttpClinet 对象并设置参数 */
        HttpClient httpClient = new HttpClient();
        // 设置 Http 连接超时为5秒
        httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(SocketTimeout);
      /* 2 生成 GetMethod 对象并设置参数 */
        GetMethod getMethod = new GetMethod(url);
        // 设置 get 请求超时为 5 秒
        getMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, SocketTimeout);
        // 设置请求重试处理,用的是默认的重试处理:请求三次
        getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());
        String response = "";
      /* 3 执行 HTTP GET 请求 */
        try {
            int statusCode = httpClient.executeMethod(getMethod);
            logger.info("get请求{}",statusCode);
         /* 4 判断访问的状态码 */
            if (statusCode != HttpStatus.SC_OK&&statusCode != HttpStatus.SC_CREATED&&statusCode != HttpStatus.SC_NO_CONTENT) {
                logger.error("请求出错: "+ getMethod.getStatusLine());
                return response;
            }
            // 读取 HTTP 响应内容,这里简单打印网页内容
            byte[] responseBody = getMethod.getResponseBody();// 读取为字节数组
            response = new String(responseBody, ContentEncoding);
            logger.info("----------response:" + response);
            // 读取为 InputStream,在网页内容数据量大时候推荐使用
            // InputStream response = getMethod.getResponseBodyAsStream();
        } catch (HttpException e) {
            // 发生致命的异常,可能是协议不对或者返回的内容有问题
            logger.error("请检查输入的URL!");
            e.printStackTrace();
        } catch (IOException e) {
            // 发生网络异常
            logger.error("发生网络异常!");
            e.printStackTrace();
        } finally {
         /* 6 .释放连接 */
            getMethod.releaseConnection();
        }
        return response;
    }

    /**
     * HttpClient PUT请求
     * @author huang
     * @date 2013-4-10
     * @return
     */
    public static String doPut(String uri,String jsonObj){
        logger.info("put请求{},{}",uri,jsonObj);

        String resStr = "";
        HttpClient htpClient = new HttpClient();
        PutMethod putMethod = new PutMethod(uri);
        putMethod.addRequestHeader( "Content-Type","application/json" );
        putMethod.getParams().setParameter( HttpMethodParams.HTTP_CONTENT_CHARSET, ContentEncoding );
        putMethod.setRequestBody( jsonObj );
        try{
            int statusCode = htpClient.executeMethod( putMethod );
            logger.info("put请求{}",statusCode);
            if (statusCode != HttpStatus.SC_OK&&statusCode != HttpStatus.SC_CREATED&&statusCode != HttpStatus.SC_NO_CONTENT) {
                logger.error("Method failed: "+putMethod.getStatusLine() );
                return resStr;
            }
            byte[] responseBody = putMethod.getResponseBody();
            resStr = new String(responseBody,ContentEncoding);
            logger.info("response:" + resStr);
        }catch(Exception e){
            logger.error(" failed: " + e.getMessage());
            e.printStackTrace();
        }finally{
            putMethod.releaseConnection();
        }
        return resStr;
    }

    /**
     * post请求
     * @param url
     * @param jsonObj
     * @return
     */
    @SuppressWarnings({ "resource" })
    public static String doPost(String url,String jsonObj){
        logger.info("post请求{},{}",url,jsonObj);

        DefaultHttpClient client = new DefaultHttpClient();
        HttpPost post = new HttpPost(url);
        post.setHeader("Content-Type", "application/json; charset=UTF-8");
        String response = "";
        try {
            StringEntity stringEntity = new StringEntity( jsonObj,"UTF-8");
            stringEntity.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
            post.setEntity(stringEntity);
            HttpResponse res = client.execute(post);
            int statusCode=res.getStatusLine().getStatusCode();
            logger.info("post请求",statusCode);
            if (statusCode != HttpStatus.SC_OK&&statusCode != HttpStatus.SC_CREATED&&statusCode != HttpStatus.SC_NO_CONTENT) {
                logger.error("Method failed: "+res.getStatusLine() );
                return response;
            }
            response = EntityUtils.toString(res.getEntity());// 返回json格式:
            logger.info("----------response:" + response);
        } catch (Exception e) {
            logger.error(" failed: " + e.getMessage());
            e.printStackTrace();
        }
        return response;
    }

    public static String doDelete(String uri)  {
        logger.info("delete请求",uri);

        String data= "";
        HttpClient httpClient= new HttpClient();
        httpClient.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, ContentEncoding);
        DeleteMethod method = null;
        try{
            method= new DeleteMethod();
            method.setURI(new URI(uri,false));
            method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());
            method.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, SocketTimeout);
            int statusCode = httpClient.executeMethod(method);
            logger.info("delete请求",statusCode);
            if (statusCode != HttpStatus.SC_OK&&statusCode != HttpStatus.SC_CREATED&&statusCode != HttpStatus.SC_NO_CONTENT) {
                logger.error("Method failed: " + method.getStatusLine());
                return data;
            }
            data= new String(method.getResponseBody(),ContentEncoding);
            logger.info("response:" + data);
        }catch(HttpException e){
            e.printStackTrace();
            logger.error("Please check your provided http address!");
        }catch(IOException e){
            e.printStackTrace();
            logger.error(e.getMessage());
        }catch(Exception e){
            e.printStackTrace();
            logger.error(e.getMessage());
        }finally{
            if(method!=null)
                method.releaseConnection();
        }
        return data;
    }

    public static void main(String args[]) {

    }
}

原文地址:https://www.cnblogs.com/aizj/p/9323101.html

时间: 2024-08-29 02:52:18

httpclient 封装 http(get put post delete)请求的相关文章

使用HttpClient 发送 GET、POST(FormData、Raw)、PUT、Delete请求及文件上传

httpclient4.3.6 package org.caeit.cloud.dev.util; import java.io.File; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.List; import java.util.Map;

JavaWeb之抓包之旅(三) :HttpClient封装工具类

谈到httpClient相信大家都不陌生,网上也有一大推别人总结的.HttpClient是Apache Jakarta Common下的子项目,用来提供高效的.最新的.功能丰富的支持HTTP协议的客户端编程工具包,并且它支持HTTP协议最新的版本和建议. 详细请参考文档:HttpClient 我们在对数据进行请求的时候经常使用. 前不久在做一个百度地图定位的(通过GPS判断你在某个学校,但是并不是每个学校地图上都有,而且如何确定范围呢?) 类似于饿了么,我一直在想它为什么能定位到具体的某个宿舍呢

WebAPI IIS PUT和DELETE请求失败

IIS拒绝PUT和DELETE请求是由于IIS为网站默认注册的一个名为WebDAVModule的自定义HttpModule导致的,如果我们的站点不需要提供针对WebDAV的支持,解决这个问题最为直接的方式就是利用如下配置将注册的HttpModule移除即可: 1 <system.webServer> 2 <modules runAllManagedModulesForAllRequests="true"> 3 <remove name="WebD

Ajax中Put和Delete请求传递参数无效的解决方法(Restful风格)

本文装载自:http://blog.csdn.net/u012737182/article/details/52831008    感谢原文作者分享 开发环境:Tomcat9.0 在使用Ajax实现Restful的时候,有时候会出现无法Put.Delete请求参数无法传递到程序中的尴尬情况,此时我们可以有两种解决方案:1.使用地址重写的方法传递参数.2.配置web.xml项目环境. 测试的程序为: @RequestMapping(value = "/member", method =

SpringMVC表单中post请求转换为put或delete请求

1.在web.xml文件中配置 1  <!-- HiddenHttpMethodFilter过滤器可以将POST请求转化为put请求和delete请求! --> 2    <filter> 3     <filter-name>hiddenHttpMethodFilter</filter-name> 4     <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter&

php在IIS上put,delete请求报404

方法一:配置C:\Windows\System32\inetsrv\Config\applicationHost.conf的put,delete 方法二:网传最广之方法,修改项目的web.config文件,在<system.webServer></system.webServer>里面贴上下面代码,移除WebDAVModule <modules runAllManagedModulesForAllRequests="true"> <remove

如何使用HttpClient来发送带客户端证书的请求,以及如何忽略掉对服务器端证书的校验

最近要做客户端和服务器端的双向认证,在客户端向服务器端发送带证书的请求这里有一点问题,网上的例子大多都不太好使,于是找了github上httpclient源代码中的例子改造了一下,终于弄明白了 github上我参考的例子在:https://github.com/apache/httpclient/blob/4.5.x/httpclient/src/examples/org/apache/http/examples/client/ClientCustomSSL.java 下面先贴上我自己的代码(需

WebAPI IIS PUT和DELETE请求失败 405

IIS拒绝PUT和DELETE请求是由于IIS为网站默认注册的一个名为WebDAVModule的自定义HttpModule导致的,如果我们的站点不需要提供针对WebDAV的支持,解决这个问题最为直接的方式就是利用如下配置将注册的HttpModule移除即可: 1 <system.webServer> 2 <modules runAllManagedModulesForAllRequests="true"> 3 <remove name="WebD

ABP PUT、DELETE请求错误405.0 - Method Not Allowed 因为使用了无效方法(HTTP 谓词) 引发客户端错误 No &#39;Access-Control-Allow-Origin&#39; header is present on the requested resource

先请检查是否是跨域配置问题,请参考博客:http://www.cnblogs.com/donaldtdz/p/7882225.html 一.问题描述 ABP angular前端部署后,查询,新增都没问题,但更新和删除会报一个跨域问题的错误,详细信息如下: PUT http://localhost:8060/api/services/app/User/Update 405 (Method Not Allowed) users:1 Failed to load http://localhost:80