JAVA的http请求几种方式

http访问是java经常使用的。一般有三种请求方式。

  1. java原生的HttpURLConnection
  2. HTTPClient3(commons-httpclient) 第三方框架
  3. HTTPClient4.5(apache.httpclient)

HttpURLConnection传入参数用OutputStream(传参使用aa=bb样式),取返回值用InputStream,请求头setRequestProperty()

public static void doPost(String url){
        HttpURLConnection connection = null;
        String params = "param=zhangsan";
        try {
            URI uri = new URI(url);
            connection = (HttpURLConnection)uri.toURL().openConnection();
            //设置讲求时长
            connection.setConnectTimeout(2000);
            //设置读的时间
            connection.setReadTimeout(1000);
            //get请求传入GET
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-Type","application/json;charset=UTF-8");
            //设置是否将数据写入链接
            connection.setDoOutput(true);
            OutputStream outputStream = connection.getOutputStream();
            outputStream.write(params.getBytes());
            outputStream.flush();
            outputStream.close();

            //发起请求
            connection.connect();

            if(connection.getResponseCode() == 200){
                InputStream inputStream = connection.getInputStream();
                byte[] bytes = new byte[1024];
                inputStream.read(bytes);
                System.out.println(new String(bytes,"utf-8"));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

httpClient3.1请求头使用setRequestHeader(),参数使用addParameter(),返回值还是使用InputStream

public static void doPost(String url, Map<String, String> params) {
        //创建HttpClient实例
        HttpClient httpClient = new HttpClient();
        //设置httpClient连接主机服务器的超时时间
        httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(2000);
        //创建Post请求方法实例
        PostMethod post = new PostMethod(url);
        post.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
        //设置Post请求时长
        post.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 2000);

        post.addParameter("param", "lisi");
        try {
            int statuCode = httpClient.executeMethod(post);
            if (200 == statuCode) {
                InputStream responseBodyAsStream = post.getResponseBodyAsStream();
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(responseBodyAsStream));
                String team = null;
                while ((team = bufferedReader.readLine()) != null) {
                    System.out.println(team);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

httpClient4.5请求头使用setHeader(),传入参数使用setEntity(),返回参数又进行了封装直接使用httpResponse.getEntity()

public static void doPost(String url, Map<String, String> params) {
        //通过默认配置创建个HttpClient实例
        CloseableHttpClient client = HttpClients.createDefault();
        CloseableHttpResponse httpResponse = null;
        //创建httpPost远程实例
        HttpPost post = new HttpPost(url);
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(2000)//连接主机服务超时时间
                .setConnectionRequestTimeout(2000)//连接请求超时时间
                .setSocketTimeout(2000)//读取数据超时时间
                .build();
        //为httpPost实例设置配置(get请求httpGet)
        post.setConfig(requestConfig);
        //设置请求头
        post.setHeader("Content-Type", "application/json;charset=UTF-8");

        //迭代请求参数map
        List<NameValuePair> nvps = new ArrayList<>();
        params.forEach((m, v) -> {
            nvps.add(new BasicNameValuePair(m, v));
        });

        //为httpPost设置封装好的请求参数
        try {
            post.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        try {
            //httpClient对象执行Post请求,并返回响应对象
            httpResponse = client.execute(post);
            HttpEntity entity = httpResponse.getEntity();
            System.out.println(EntityUtils.toString(entity));
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭资源
            if (null != httpResponse) {
                try {
                    httpResponse.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != client) {
                try {
                    client.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

在java中url和uri的区别?
uri:表示统一资源标识符引用
url:和般表示网络资源
url = uri.toUrl()

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值