java实现HTTP请求

目前JAVA实现HTTP请求的方法用的最多的有两种:
1、通过HTTPClient这种第三方的开源框架去实现。HTTPClient对HTTP的封装性比较不错,通过它基本上能够满足我们大部分的需求,HttpClient3.1 是 org.apache.commons.httpclient下操作远程 url的工具包,虽然已不再更新,但实现工作中使用httpClient3.1的代码还是很多,HttpClient4.5是org.apache.http.client下操作远程 url的工具包,最新的;
2、通过HttpURLConnection去实现,HttpURLConnection是JAVA的标准类,是JAVA比较原生的一种实现方式。

1、第一种方式:java原生HttpURLConnection

使用Java自带的java.io和java.net包。
get请求

 /**
     * get请求
     * @param httpUrl
     * @return
     */
    public static String doGet(String httpUrl) {
        //链接
        HttpURLConnection connection = null;
        InputStream is = null;
        BufferedReader br = null;
        // 存放数据
        StringBuffer result = new StringBuffer();
        try {
            //创建远程url连接对象
            URL url = new URL(httpUrl);
            //通过远程url连接对象打开一个连接,强转成httpURLConnection类
            connection = (HttpURLConnection) url.openConnection();
            //设置请求方式
            connection.setRequestMethod("GET");
            //设置连接主机服务器的超时时间:15000毫秒
            connection.setConnectTimeout(15000);
            //设置读取远程返回的数据时间:60000毫秒
            connection.setReadTimeout(60000);
            // 开始连接
            connection.connect();
            // 通过connection连接,获取输入流
            if (connection.getResponseCode() == 200) {
                is = connection.getInputStream();
                if (is != null) {
                    // 封装输入流is,并指定字符集
                    br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
                    // 存放数据
                    String temp = null;
                    while ((temp = br.readLine()) != null) {
                        result.append(temp);
                        result.append("\r\n");
                    }
                }
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            connection.disconnect();// 关闭远程连接
        }
        return result.toString();
    }

测试结果:
在这里插入图片描述
被请求方法:
在这里插入图片描述
post请求

   /**
     * post请求
     * @param httpUrl
     * @param param
     * @return
     */
    public static String doPost(String httpUrl, String param) {
        StringBuffer result = new StringBuffer();
        //连接
        HttpURLConnection connection = null;
        OutputStream os = null;
        InputStream is = null;
        BufferedReader br = null;
        try {
            //创建连接对象
            URL url = new URL(httpUrl);
            //通过远程url连接对象打开连接
            connection = (HttpURLConnection) url.openConnection();
            //设置请求方法
            connection.setRequestMethod("POST");
            //设置连接主机服务器超时时间:15000毫秒
            connection.setConnectTimeout(15000);
            //设置读取主机服务器返回数据超时时间:60000毫秒
            connection.setReadTimeout(60000);
            // 设置是否可读取
            // 默认值为:false,当向远程服务器传送数据/写数据时,需要设置为true
            connection.setDoOutput(true);
            //设置响应是否可读取
            //默认值为:true,当前向远程服务读取数据时,设置为true,该参数可有可无
            connection.setDoInput(true);
            connection.setRequestProperty("Connection", "Keep-Alive");
            // 设置传入参数的格式:请求参数应该是 name1=value1&name2=value2 的形式。
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            connection.setRequestProperty("Charset","UTF-8");
            // 设置鉴权信息:Authorization: Bearer da3efcbf-0845-4fe3-8aba-ee040be542c0
            connection.setRequestProperty("Authorization",
                    "Bearer da3efcbf-0845-4fe3-8aba-ee040be542c0");
            // 通过连接对象获取一个输出流
            os = connection.getOutputStream();
            // 通过输出流对象将参数写出去/传输出去,它是通过字节数组写出的
            os.write(param.getBytes());
            // 通过连接对象获取一个输入流,向远程读取
            if (connection.getResponseCode() == 200) {
                is = connection.getInputStream();
                // 对输入流对象进行包装:charset根据工作项目组的要求来设置
                br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
                String temp = null;
                // 循环遍历一行一行读取数据
                while ((temp = br.readLine()) != null) {
                    result.append(temp);
                    result.append("\r\n");
                }
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            //关闭连接
            connection.disconnect();
        }
        return result.toString();
    }


   public static void main(String[] args) {
        //get
        System.out.println(doGet("https://www.baidu.com"));
        //post
        //设置传入参数的格式:请求参数是 name1=value1&name2=value2 的形式
        String parmam = "name=赵丹&age=20";
        System.out.println(doPost("http://localhost:8080/hello1", parmam));
    }

测试结果:
在这里插入图片描述
被请求方法:
在这里插入图片描述

2、第二种方式:使用org.apache.commons.httpclient.HttpClient;

使用org.apache.commons.httpclient的HttpClient-3.x.Jar包。

  <!-- https://mvnrepository.com/artifact/commons-httpclient/commons-httpclient -->
    <dependency>
        <groupId>commons-httpclient</groupId>
        <artifactId>commons-httpclient</artifactId>
        <version>3.1</version>
    </dependency>

get请求

/**
 * get请求方法
 * @param url
 * @return
 */
public static String doGet(String url) {
    //返回数据
    StringBuffer result = new StringBuffer();
    // 输入流
    InputStream is = null;
    BufferedReader br = null;
    // 创建httpClient实例
    HttpClient httpClient = new HttpClient();
    // 设置http连接主机服务超时时间:15000毫秒
    // 先获取连接管理器对象,再获取参数对象,再进行参数的赋值
    httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(15000);
    //创建一个Get方法实例对象
    GetMethod getMethod = new GetMethod(url);
    // 设置get请求超时为60000毫秒
    getMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 60000);
    // 设置请求重试机制,默认重试次数:3次,参数设置为true,重试机制可用,false相反
    getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, true));
    //执行get方法
    try {
        int statusCode = httpClient.executeMethod(getMethod);
        // 判断返回码
        if (statusCode != HttpStatus.OK.value()) {
            // 如果状态码返回的不是ok,说明失败了,打印错误信息
            System.err.println("Method faild: " + getMethod.getStatusLine());
        } else {
            // 通过getMethod实例,获取远程的一个输入流
            is = getMethod.getResponseBodyAsStream();
            // 包装输入流
            br = new BufferedReader(new InputStreamReader(is, "UTF-8"));

            // 读取封装的输入流
            String temp = null;
            while ((temp = br.readLine()) != null) {
                result.append(temp);
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        // 关闭资源
        if (null != br) {
            try {
                br.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (null != is) {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        // 释放连接
        getMethod.releaseConnection();
    }
    return result.toString();
}

测试结果:
在这里插入图片描述

post请求

/**
 * post方法请求
 * @param url
 * @param paramMap
 * @return
 */
public static String doPost(String url, Map<String, Object> paramMap) {
    //存储返回数据
    StringBuffer sbf = new StringBuffer();
    // 获取输入流
    InputStream is = null;
    BufferedReader br = null;
    String result = null;
    // 创建httpClient实例对象
    HttpClient httpClient = new HttpClient();

    //方法1:解决中文参数乱码的问题
    httpClient.getParams().setContentCharset("UTF-8");

    // 设置httpClient连接主机服务器超时时间:15000毫秒
    httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(15000);

    // 创建post请求方法实例对象
    PostMethod postMethod = new PostMethod(url);
    // 设置post请求超时时间
    postMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 60000);

    //方法2:解决中文参数乱码的问题
    //postMethod.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET,"UTF-8");
    //postMethod.getParams().setContentCharset("UTF-8");

    NameValuePair[] nvp = null;
    // 判断参数map集合paramMap是否为空
    if (null != paramMap && paramMap.size() > 0) {// 不为空
        // 创建键值参数对象数组,大小为参数的个数
        nvp = new NameValuePair[paramMap.size()];
        // 循环遍历参数集合map
        Set<Map.Entry<String, Object>> entrySet = paramMap.entrySet();
        // 获取迭代器
        Iterator<Map.Entry<String, Object>> iterator = entrySet.iterator();

        int index = 0;
        while (iterator.hasNext()) {
            Map.Entry<String, Object> mapEntry = iterator.next();
            // 从mapEntry中获取key和value创建键值对象存放到数组中
            try {
                nvp[index] = new NameValuePair(mapEntry.getKey(),
                        new String(mapEntry.getValue().toString().getBytes("UTF-8"), "UTF-8"));
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            index++;
        }
    }
    // 判断nvp数组是否为空
    if (null != nvp && nvp.length > 0) {
        // 将参数存放到requestBody对象中
        postMethod.setRequestBody(nvp);
    }
    // 执行POST方法
    try {
        int statusCode = httpClient.executeMethod(postMethod);
        // 判断是否成功
        if (statusCode != HttpStatus.OK.value()) {
            System.err.println("Method faild: " + postMethod.getStatusLine());
        }
        // 获取远程返回的数据
        is = postMethod.getResponseBodyAsStream();
        // 封装输入流
        br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
        String temp = null;
        while ((temp = br.readLine()) != null) {
            sbf.append(temp);
        }
        result = sbf.toString();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        // 关闭资源
        if (null != br) {
            try {
                br.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (null != is) {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        // 释放连接
        postMethod.releaseConnection();
    }
    return result;
}
public static void main(String[] args) {
    //get
    System.out.println(doGet("http://localhost:8080/hello"));

    //post
    //设置传入参数的格式:请求参数是 map 的形式
    Map<String, Object> paramMap = new HashMap<>(2);
    paramMap.put("name","赵云");
    paramMap.put("age",21);
    System.out.println(doPost("http://localhost:8080/hello1", paramMap));
}

测试结果:
在这里插入图片描述
中文乱码解决:

  //方法1:解决中文参数乱码的问题
   httpClient.getParams().setContentCharset("UTF-8");
  //方法2:解决中文参数乱码的问题
  //postMethod.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET,"UTF-8");//postMethod.getParams().setContentCharset("UTF-8");

3、第三种方式:java原生HttpURLConnection

使用org.apache.http.client的HttpClient-4.x.Jar包。

<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.12</version>
</dependency>

get请求

   /**
     * get请求
     * @param url
     * @return
     */
    public static String doGet(String url) {
        //1.获得一个httpclient对象
        CloseableHttpClient httpClient = null;
        //2.生成一个response对象
        CloseableHttpResponse response = null;
        String result = "";
        try {
            // 通过址默认配置创建一个httpClient实例
            httpClient = HttpClients.createDefault();
            // 创建httpGet远程连接实例
            HttpGet httpGet = new HttpGet(url);
            // 设置请求头信息,鉴权
            httpGet.setHeader("Authorization", "Bearer da3efcbf-0845-4fe3-8aba-ee040be542c0");
            // 设置配置请求参数
            RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(35000)// 连接主机服务超时时间
                    .setConnectionRequestTimeout(35000)// 请求超时时间
                    .setSocketTimeout(60000)// 数据读取超时时间
                    .build();
            // 为httpGet实例设置配置
            httpGet.setConfig(requestConfig);
            // 执行get请求得到返回对象
            response = httpClient.execute(httpGet);
            // 通过返回对象获取返回数据
            HttpEntity entity = response.getEntity();
            // 通过EntityUtils中的toString方法将结果转换为字符串
            result = EntityUtils.toString(entity);
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭资源
            if (null != response) {
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != httpClient) {
                try {
                    httpClient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return result;
    }

测试结果:
在这里插入图片描述

   /**
     * post请求
     * @param url
     * @param paramMap
     * @return
     */
    public static String doPost(String url, Map<String, Object> paramMap) {
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse httpResponse = null;
        String result = "";
        // 创建httpClient实例
        httpClient = HttpClients.createDefault();
        // 创建httpPost远程连接实例
        HttpPost httpPost = new HttpPost(url);
        // 配置请求参数实例
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(35000)// 设置连接主机服务超时时间
                .setConnectionRequestTimeout(35000)// 设置连接请求超时时间
                .setSocketTimeout(60000)// 设置读取数据连接超时时间
                .build();
        // 为httpPost实例设置配置
        httpPost.setConfig(requestConfig);
        // 设置请求头
        httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded");
        // 封装post请求参数
        if (null != paramMap && paramMap.size() > 0) {
            List<NameValuePair> nvps = new ArrayList<NameValuePair>();
            // 通过map集成entrySet方法获取entity
            Set<Map.Entry<String, Object>> entrySet = paramMap.entrySet();
            // 循环遍历,获取迭代器
            Iterator<Map.Entry<String, Object>> iterator = entrySet.iterator();
            while (iterator.hasNext()) {
                Map.Entry<String, Object> mapEntry = iterator.next();
                nvps.add(new BasicNameValuePair(mapEntry.getKey(), mapEntry.getValue().toString()));
            }

            // 为httpPost设置封装好的请求参数
            try {
                httpPost.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        try {
            // httpClient对象执行post请求,并返回响应参数对象
            httpResponse = httpClient.execute(httpPost);
            // 从响应对象中获取响应内容
            HttpEntity entity = httpResponse.getEntity();
            result = EntityUtils.toString(entity);
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭资源
            if (null != httpResponse) {
                try {
                    httpResponse.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != httpClient) {
                try {
                    httpClient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return result;
    }

测试结果:

public static void main(String[] args) {
    //get
    System.out.println(doGet("http://localhost:8080/hello"));

    //post
    //设置传入参数的格式:请求参数是 map 的形式
    Map<String, Object> paramMap = new HashMap<>(2);
    paramMap.put("name", "张飞");
    paramMap.put("age", 22);
    System.out.println(doPost("http://localhost:8080/hello1", paramMap));
}

在这里插入图片描述

有时候我们在使用post请求时,可能传入的参数是json或者其他格式,此时我们则需要更改请求头及参数的设置信息,以httpClient4.5为例,更改下面两列配置:httpPost.setEntity(new StringEntity(“你的json串”)); httpPost.addHeader(“Content-Type”, “application/json”)。

  • 1
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java中,有多种方式可以实现HTTP请求。其中一种常见的方式是使用Java标准库中的HttpURLConnection类。这个类提供了发送HTTP请求和接收HTTP响应的功能。你可以使用HttpURLConnection类创建连接,并设置请求方法、请求头、请求体等,然后发送请求并获取响应。具体的代码可以参考以下示例: ``` import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; public class HttpExample { public static void main(String[] args) throws IOException { URL url = new URL("https://www.example.com"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); // 设置请求方法,例如GET、POST等 connection.setConnectTimeout(5000); // 设置连接超时时间 connection.setReadTimeout(5000); // 设置读取超时时间 int responseCode = connection.getResponseCode(); // 获取响应码 if (responseCode == HttpURLConnection.HTTP_OK) { InputStream inputStream = connection.getInputStream(); // 处理响应数据 } else { // 处理错误情况 } connection.disconnect(); // 断开连接 } } ``` 另外,你还可以使用第三方库来简化HTTP请求的过程,比如OkHttp和Spring的RestTemplate。使用OkHttp时,你可以创建一个OkHttpClient实例,并使用Request类来构建请求,然后发送请求并获取响应。以下是一个使用OkHttp的示例代码: ``` import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; import java.io.IOException; public class OkHttpExample { private static final OkHttpClient client = new OkHttpClient(); public static void main(String[] args) throws IOException { Request request = new Request.Builder() .url("https://www.example.com") .build(); try (Response response = client.newCall(request).execute()) { String result = response.body().string(); System.out.println(result); } } } ``` 如果你使用Spring框架,你可以使用RestTemplate类来发送HTTP请求。RestTemplate封装了HTTP请求的各种方法,让你可以更方便地发送请求和处理响应。以下是一个使用RestTemplate的示例代码: ``` import org.springframework.http.ResponseEntity; import org.springframework.web.client.RestTemplate; public class RestTemplateExample { public static void main(String[] args) { RestTemplate restTemplate = new RestTemplate(); ResponseEntity<String> response = restTemplate.getForEntity("https://www.example.com", String.class); String result = response.getBody(); System.out.println(result); } } ``` 以上是三种常见的Java实现HTTP请求的方法,你可以根据具体的需求选择适合的方式来发送HTTP请求。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* *3* [Java 实现HTTP请求的四种方式总结](https://blog.csdn.net/qq_34383510/article/details/130627924)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 100%"] [ .reference_list ]

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值