使用ApacheHttp创建请求

本文介绍如何使用Java实现GET和POST请求处理,包括普通表单、XML及JSON数据的发送方法。通过具体示例代码,展示了如何配置请求超时、设置请求头及处理响应数据。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.get请求

 public static String httpGet(String url) throws IOException {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectTimeout(5000)   //设置连接超时时间
                .setConnectionRequestTimeout(5000) // 设置请求超时时间
                .setSocketTimeout(5000)
                .setRedirectsEnabled(true)//默认允许自动重定向
                .build();
        HttpGet httpGet = new HttpGet(url);
        httpGet.setConfig(requestConfig);
        HttpResponse httpResponse = httpClient.execute(httpGet);
        HttpEntity entity = httpResponse.getEntity();

        String srtResult = EntityUtils.toString(entity);//获得返回的结果
        httpClient.close();
        return srtResult;
    }

2.使用BasicNameValuePair模拟表单发送post请求

    /**
     * List<BasicNameValuePair> list = new ArrayList<BasicNameValuePair>();
     * list.add(new BasicNameValuePair("age", "20"));  //请求参数(只能为字符串)
     * list.add(new BasicNameValuePair("name", "zhangsan")); //请求参数
     * @param url
     * @param list
     * @return
     */
    public static String httpPost(String url,List<BasicNameValuePair> list) throws IOException {
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        HttpPost post = new HttpPost(url);
        //如果有header请求,添加header请求
        //post.addHeader("x-api-key", "XXX");
        //post.addHeader("x-lang", "en-US");

        UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list,"UTF-8");
        //设置post求情参数
        post.setEntity(entity);
        //向服务器发送请求,并获取返回数据
        CloseableHttpResponse response = httpClient.execute(post);
        response.getStatusLine().getStatusCode();

        //获取HttpEntity消息载体对象
        HttpEntity news = response.getEntity();
        // EntityUtils中的toString()方法转换服务器的响应数据
        String str = EntityUtils.toString(news, "utf-8");

        httpClient.close();
        return str;
    }

3.发送xml类型的post请求

    /**
     * 
     * @param url
     * @param xmlData (xml字符串)
     * @return result (String字符串)
     * @throws Exception
     */
    public String httpPost(String url, String xmlData) throws Exception {
        HttpClient client=HttpClients.createDefault();
        HttpPost post = new HttpPost(url);
        List<BasicNameValuePair> parameters = new ArrayList();
        parameters.add(new BasicNameValuePair("xml", xmlData));
        post.setEntity(new UrlEncodedFormEntity(parameters,"UTF-8"));
        HttpResponse response = client.execute(post);
        System.out.println(response.toString());
        HttpEntity entity = response.getEntity();
        String result = EntityUtils.toString(entity, "UTF-8");
        return result;
    }

4.发送JSONObject参数的post请求

    /**
     * JSONObject jsonParam = new JSONObject();
     * jsonParam.put("name", "admin");
     * jsonParam.put("pass", "123456");
     * @param url
     * @param jsonParam
     * @return
     * @throws IOException
     */
    public static String httpPost(String url,JSONObject jsonParam) throws IOException {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost post = new HttpPost(url);
        StringEntity entity = new StringEntity(jsonParam.toString(),"utf-8");
        entity.setContentEncoding("UTF-8");
        entity.setContentType("application/json");
        post.setEntity(entity);
        CloseableHttpResponse response = httpClient.execute(post);
        HttpEntity news = response.getEntity();
        String str = EntityUtils.toString(news, "utf-8");
        httpClient.close();
        return str;
    }

5.第二种方式创建http请求

    public static String httpGet(String url) throws IOException {
        CloseableHttpClient httpClient= HttpClients.createDefault(); // 创建httpClient实例
        HttpGet httpGet=new HttpGet(url); // 创建httpget实例
        httpGet.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:50.0) Gecko/20100101 Firefox/50.0"); // 设置请求头消息User-Agent
        CloseableHttpResponse response=httpClient.execute(httpGet); // 执行http get请求
        HttpEntity entity=response.getEntity(); // 获取返回实体
        response.close(); // response关闭
        httpClient.close(); // httpClient关闭
        return EntityUtils.toString(entity, "utf-8");
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值