jdk-httpclient

jdk-httpclient

jdk自带发送http请求的类,不需要第三方依赖

发送get请求和post请求

发送get请求

BufferedReader in = null;
StringBuffer strBuf = new StringBuffer();
try {
  URL realUrl = new URL(url);
  // 打开和URL之间的连接
  URLConnection conn = realUrl.openConnection();
  // 定义BufferedReader输入流来读取URL的响应
  InputStreamReader inputStreamReader = new InputStreamReader(conn.getInputStream());
  in = new BufferedReader(inputStreamReader);
  String line;
  while ((line = in.readLine()) != null) {
    strBuf.append(line);
    strBuf.append("\r\n");
  }
} catch (IOException e) {
  e.printStackTrace();
} finally {
  if (in != null) {
    try {
      in.close();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}

设置请求参数

conn.setRequestProperty("content-type", "application/json");

封装一个简单的get方法

public StringBuffer get(String url, Map<String, String> headers) {
  URLConnection conn = null;
  try {
    URL realUrl = new URL(url);
    conn = realUrl.openConnection();
  } catch (IOException e1) {
    e1.printStackTrace();
  }
  if (headers != null) {
    for (Map.Entry<String, String> e : headers.entrySet()) {
      conn.setRequestProperty(e.getKey(), e.getValue());
    }
  }
  // 定义BufferedReader输入流来读取URL的响应
  BufferedReader in = null;
  StringBuffer strBuf = new StringBuffer();

  try {
    InputStreamReader inputStreamReader = new InputStreamReader(conn.getInputStream());
    in = new BufferedReader(inputStreamReader);
    String line;
    while ((line = in.readLine()) != null) {
      strBuf.append(line);
      strBuf.append("\r\n");
    }
  } catch (IOException e) {
    e.printStackTrace();
  } finally {
    try {
      in.close();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
  return strBuf;
}

使用get方法

Map<String, String> hdeader = new HashMap<>();
hdeader.put("content-type", "application/json");
StringBuffer strBuf = get(url, hdeader);

发送post请求

发送 post json

PrintWriter out = null;
BufferedReader in = null;
String result = "";
try {
  URL realUrl = new URL(url);
  // 打开和URL之间的连
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值