Apache HttpClient

HttpClient的请求方式有很多,其实本质都一样,下面我来介绍一下,Apache中的HttpClient

一、首先我们需要将Apache HttpClient的依赖包引用进来

<dependency>
<span style="white-space:pre">	</span><groupId>commons-httpclient</groupId>
<span style="white-space:pre">	</span><artifactId>commons-httpclient</artifactId>
<span style="white-space:pre">	</span><version>3.1</version>
</dependency>

二、请求有两种,分别是Http和Https

1、Http

public static String sendJsonWithHttp(String surl, String json) throws Exception
    {
        URL url = new URL(surl);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestProperty("Content-Type", "application/json;charset=utf-8");
        conn.setRequestMethod("POST");// 提交模式
        conn.setRequestProperty("Content-Length", json.getBytes().length + "");
        conn.setConnectTimeout(100000);// 连接超时单位毫秒 //
        conn.setReadTimeout(200000);// 读取超时 单位毫秒
        conn.setDoOutput(true);// 是否输入参数
        conn.setDoInput(true);
        conn.setUseCaches(false);
        conn.connect();
        DataOutputStream out = new DataOutputStream(conn.getOutputStream());
        out.write(json.getBytes());
        out.flush();
        out.close();
        BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        StringBuffer sb = new StringBuffer();
        String line;
        while ((line = reader.readLine()) != null)
        {
            sb.append(line);
        }
        reader.close();
        conn.disconnect();
        return sb.toString();
    }

2、Https

    final static String PROTOCOL_NAME = "https";

    public static String sendJsonWithHttps(String surl, String json) throws Exception
    {
        HttpClient client = new HttpClient();
        client.getParams().setContentCharset("UTF-8");
        Protocol httpProtocol = new Protocol(PROTOCOL_NAME, new SSLProtocolSocketFactory(false), 443);
        Protocol.registerProtocol(PROTOCOL_NAME, httpProtocol);
        PostMethod post = new PostMethod(surl);
        post.setRequestHeader("Content-Type", "application/json");
        RequestEntity requestEntity = new ByteArrayRequestEntity(json.getBytes("utf-8"));
        post.setRequestEntity(requestEntity);
        client.executeMethod(post);
        InputStream in = post.getResponseBodyAsStream();
        byte[] buf = new byte[512];
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        do
        {
            int n = in.read(buf);
            if (n > 0)
            {
                baos.write(buf, 0, n);
            }
            else if (n <= 0)
            {
                break;
            }
        } while (true);
        return baos.toString();
    }

仅供参考!

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值