Java教程

java http请求

本文主要是介绍java http请求,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
    public static void http(String url,JSONObject object){

        try{
            CloseableHttpClient httpClient = HttpClientBuilder.create().build();
            HttpPost httpPost = new HttpPost(url);
            // 我这里利用阿里的fastjson,将Object转换为json字符串;
            // (需要导入com.alibaba.fastjson.JSON包)
//            System.err.println("上传的data为:"+object.get("data"));
            String jsonString = JSON.toJSONString(object);
            StringEntity entity = new StringEntity(jsonString, "UTF-8");
            // post请求是将参数放在请求体里面传过去的;这里将entity放入post请求体中
            httpPost.setEntity(entity);
            httpPost.setHeader("Content-Type", "application/json;charset=utf8");
            // 响应模型
            CloseableHttpResponse response = null;
            try {
                // 由客户端执行(发送)Post请求
                response = httpClient.execute(httpPost);
                // 从响应模型中获取响应实体
                HttpEntity responseEntity = response.getEntity();
                System.out.println("响应状态为:" + response.getStatusLine());
                if (responseEntity != null) {
                    System.out.println("响应内容长度为:" + responseEntity.getContentLength());
                    String s = EntityUtils.toString(responseEntity);
                    System.out.println("响应内容为:" +s);
                    //解析json
                    JSONObject jsonObject=JSONObject.parseObject(s);


                }
            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (ParseException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    // 释放资源
                    if (httpClient != null) {
                        httpClient.close();
                    }
                    if (response != null) {
                        response.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }catch (Exception e){
            e.printStackTrace();

        }
    }

 

这篇关于java http请求的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!