盘点JAVA发送HTTP请求的四种方式

本文详细介绍了JAVA中发送HTTP请求的四种方式:HttpURLConnection、URLConnection、HttpClient和Socket。HttpURLConnection作为URLConnection的子类,提供了更多便利的方法。HttpClient虽然使用简便但需要额外的jar包。Socket虽然无需额外依赖,但使用相对复杂。总结了每种方式的特点,为开发者提供了选择参考。
摘要由CSDN通过智能技术生成

这篇文章主要给大家介绍了关于JAVA发送HTTP请求的多种方式,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着微点阅读小编来一起学习学习吧

1. HttpURLConnection

使用JDK原生提供的net,无需其他jar包;

HttpURLConnection是URLConnection的子类,提供更多的方法,使用更方便。

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

package httpURLConnection;

import java.io.BufferedReader;

import java.io.InputStream;

import java.io.InputStreamReader;

import java.net.HttpURLConnection;

import java.net.URL;

public class HttpURLConnectionHelper {

 public static String sendRequest(String urlParam,String requestType) {

  HttpURLConnection con = null;

  BufferedReader buffer = null;

  StringBuffer resultBuffer = null;

  try {

   URL url = new URL(urlParam);

   //得到连接对象

   con = (HttpURLConnection) url.openConnection();

   //设置请求类型

   con.setRequestMethod(requestType);

   //设置请求需要返回的数据类型和字符集类型

   con.setRequestProperty("Content-Type", "application/json;charset=GBK");

   //允许写出

   con.setDoOutput(true);

   //允许读入

   con.setDoInput(true);

   //不使用缓存

   con.setUseCaches(false);

   //得到响应码

   int responseCode = con.getResponseCode();

   if(responseCode == HttpURLConnection.HTTP_OK){

    //得到响应流

    InputStream inputStream = con.getInputStream();

    //将响应流转换成字符串

    resultBuffer = new StringBuffer();

    String line;

    buffer = new BufferedReader(new InputStreamReader(inputStream, "GBK"));

    while ((line = buffer.readLine()) != null) {

     resultBuffer.append(line);

    }

    return resultBuffer.toString();

   }

  }catch(Exception e) {

   e.printStackTrace();

  }

  return "";

 }

 public static void main(String[] args) {

  String url ="http://int.dpool.sina.com.cn/iplookup/iplookup.php?ip=120.79.75.96";

  System.out.println(sendRequest(url,

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值