一、发送json

    public void test() throws IOException {
//参数封装------------------------------------------------------
Map<String, Object> jsonMap = new HashMap<String, Object>();
Map<String, Object> params1 = new HashMap<String, Object>();
List<Object> params2=new ArrayList<>();
//封装params1
//封装params2
//封装jsonMap
jsonMap.put("sendBasic", params1);
jsonMap.put("toUsers", params2);
String json = JSON.toJSONString(jsonMap);
//---建立连接---------------------------------------------------------------
URL url = new URL("http://");//请求的路径
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true); // 设置可输入
connection.setDoOutput(true); // 设置该连接是可以输出的
connection.setRequestMethod("POST");// 设置请求方式
connection.setRequestProperty("Charset", "UTF-8");
connection.setRequestProperty("Accept-Charset", "utf-8");
connection.setRequestProperty("Content-Type", "application/json;charset=utf-8"); //发送参数---------------------------------------------------------------------------
BufferedOutputStream pw = new BufferedOutputStream(connection.getOutputStream());
//发送内容转码utf-8 **必写**
pw.write(json.getBytes("UTF-8"));
pw.flush();
pw.close();
//读取响应数据---------------------------------------------------------------------------
//输入流转码utf-8 **必写**
BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
String line = null;
StringBuilder result = new StringBuilder();
while ((line = br.readLine()) != null) { // 读取数据
result.append(line + "\n");
}
}

httpUtil工具类

import java.io.*;
import java.net.*; import javax.net.ssl.HttpsURLConnection;
import javax.servlet.http.HttpServletRequest; /**
* http请求工具类
*
*/
public class HttpUtil2 { /**
* @Description
* @Date 15:36 2022-10-13
* @Param String url
* @Param boolean isSSL
* @Param int timeout
* @return java.net.URLConnection
*/
private static URLConnection getConn(String url, boolean isSSL,int timeout){
URL realUrl = null;
URLConnection connection = null;
try {
realUrl = new URL(url);
realUrl.openConnection();// 打开和URL之间的连接
// 开发环境打开和URL之间的连接
// Proxy proxy1 = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("代理ip", 80)); //设置代理
// URLConnection connection = realUrl.openConnection(proxy1);// 打开和URL之间的连接
if (isSSL) {
connection = (HttpsURLConnection) connection;
}
// 设置通用的请求属性
connection.setRequestProperty("accept", "*/*");
connection.setRequestProperty("connection", "Keep-Alive");
connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
// 建立实际的连接
connection.setConnectTimeout(timeout);//连接失效时间 1s
connection.connect();
} catch (Exception e) {
System.out.println("发送GET请求出现异常!" + e);
e.printStackTrace();
} return connection; } public static String get(String url){
return get(url,false);
} /**
* 发送get请求
* @param url 链接地址
* @param isSSL 是否是https协议
* @return 返回响应字符串
*/
public static String get(String url, boolean isSSL) { String result = "";
BufferedReader in = null;
try {
URLConnection connection = getConn(url, false, 1000);
// 定义 BufferedReader输入流来读取URL的响应
in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
System.out.println("发送GET请求出现异常!" + e);
} finally {
// 使用finally块来关闭输入流
try {
if (in != null) {
in.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
return result;
} /**
* 发送get请求
* @param url 链接地址
* @param localPath 保存到本地的全路径
* @param isSSL 是否是https协议
* @return 返回响应字符串
*/
public static String getPic(String url, String localPath,boolean isSSL) { String result = "";
BufferedReader in = null;
try {
URLConnection connection = getConn(url, false, 1000);
InputStream inputStream = connection.getInputStream();
OutputStream outputStream = new FileOutputStream(localPath);
byte[] buffer = new byte[1024];
//每次读取的字符串长度,如果为-1,代表全部读取完毕
int len = 0;
//使用一个输入流从buffer里把数据读取出来
while( (len=inputStream.read(buffer)) != -1 ){
outputStream.write(buffer,0,len);
}
// 关闭输出流
inputStream.close();
outputStream.close(); } catch (Exception e) {
System.out.println("发送GET请求出现异常!" + e);
} finally {
// 使用finally块来关闭输入流
try {
if (in != null) {
in.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
return result;
} /**
* 发送post请求
* @param reqUrl
* @param params
* @param isSSL
* @return
*/
public static String post(String reqUrl, String params, boolean isSSL)
{
HttpURLConnection connection = null;
String responseContent = null;
try
{
URL url = new URL(reqUrl);
connection = (HttpURLConnection) url.openConnection();
if (isSSL) {
connection = (HttpsURLConnection) connection;
}
connection.setRequestMethod("POST");
connection.setConnectTimeout(1000);
connection.setDoOutput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
connection.connect();
OutputStreamWriter osw = new OutputStreamWriter(connection.getOutputStream(), "utf-8");
osw.write(params);
osw.flush();
osw.close(); InputStream in = connection.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(in));
String tempLine = rd.readLine();
StringBuffer tempStr = new StringBuffer();
String crlf=System.getProperty("line.separator");
while (tempLine != null)
{
tempStr.append(tempLine);
tempStr.append(crlf);
tempLine = rd.readLine();
}
responseContent = tempStr.toString();
rd.close();
in.close();
}
catch (IOException e)
{
System.out.println("发送POST请求出现异常!" + e);
}
finally
{
if (connection != null)
{
connection.disconnect();
}
}
return responseContent;
} /**
* 获取http请求体
* @param request
* @return
* @throws IOException
*/
public static String getHttpBody(HttpServletRequest request) throws IOException{
BufferedReader br = request.getReader(); String str, wholeStr = "";
while((str = br.readLine()) != null){
wholeStr += str;
}
return wholeStr;
} public static void main(String[] args) {
} }

java功能-发送http请求的更多相关文章

  1. java httpclient发送json 请求 ,go服务端接收

    /***java客户端发送http请求*/package com.xx.httptest; /** * Created by yq on 16/6/27. */ import java.io.IOEx ...

  2. java中发送http请求的方法

    package org.jeecgframework.test.demo; import java.io.BufferedReader; import java.io.FileOutputStream ...

  3. 用java代码发送http请求

    //发送post请求 PrintWriter out = null; BufferedReader in = null; String result = ""; try { URL ...

  4. 对于java用发送http请求,请求内容为xml格式

    import java.io.BufferedInputStream; import java.io.BufferedReader; import java.io.ByteArrayOutputStr ...

  5. java内部发送http请求并取得返回结果,修改response的cookie

    public Object userLogin(HttpServletRequest request, HttpServletResponse response, String email, Stri ...

  6. java 模拟发送post请求测试

    方法一: HttpClient public void postTest(HttpServletRequest request,Integer type,String phone,String pas ...

  7. java okhttp发送post请求

    java的httpclient和okhttp请求网络,构造一个基本的post get请求,都比py的requests步骤多很多,也比py的自带包urllib麻烦些. 先封装成get post工具类,工 ...

  8. Java HttpURLConnection发送post请求示例

    public static Map<String, Object> invokeCapp(String urlStr, Map<String, Object> params) ...

  9. Java httpClient 发送http请求

    RestTemplate ObjectMapper将string反序列化为WeatherResponse类 RestTemplate通过spring配置注入

  10. Java学习笔记--通过java.net.URLConnection发送HTTP请求

    http://www.cnblogs.com/nick-huang/p/3859353.html 使用Java API发送 get请求或post请求的步骤: 1. 通过统一资源定位器(java.net ...

随机推荐

  1. Docker 容器基本操作(基础)

    拉钩教育App版权问题,如果转载请附带拉钩教育等信息 一,什么是容器 容器是基于镜像创建的可运行实例,并且单独存在,一个镜像可以创建出多个容器 二.容器生命周期,五个状态 stopped : 停止状态 ...

  2. docker部署rocketmq

    docker pull foxiswho/rocketmq:server-4.7.0  (拉取镜像) docker pull foxiswho/rocketmq:broker-4.7.0 (拉取镜像) ...

  3. win10:你需要来自XXXX的权限才能对此文件夹进行更改

    转载请注明来源:https://www.cnblogs.com/Sherlock-L/p/16769720.html 起因 软件运行失败,看报错信息是删除某个文件夹失败了,行吧,我自己来删.找到目标文 ...

  4. js 实例对象 面向对象编程

      1.对象是什么 面向对象编程(Object Oriented Programming,缩写为 OOP)是目前主流的编程范式.它将真实世界各种复杂的关系,抽象为一个个对象,然后由对象之间的分工与合作 ...

  5. AWT+Swing区别

    AWT 是Abstract Window ToolKit (抽象窗口工具包)的缩写,这个工具包提供了一套与本地图形界面进行交互的接口.AWT 中的图形函数与操作系统所提供的图形函数之间有着一一对应的关 ...

  6. [转]Windows 批处理命令教程

    第一章 批处理基础 第一节 常用批处理内部命令简介 批处理定义:顾名思义,批处理文件是将一系列命令按一定的顺序集合为一个可执行的文本文件,其扩展名为BAT或者CMD.这些命令统称批处理命令.小知识:可 ...

  7. 【笔记】archlinux缺少部分常用工具

    安装archlinux之后发现缺少很多常用工具 比如ifconfig ftp等 ifconfig需要安装net-tools nslookup需要dnsutils ftp需要inetutils 另外安装 ...

  8. Kubernetes理论知识

    一.k8s概念 Kubernetes(k8s)是跨主机集群的自动部署.扩展以及运行应用程序容器的开源平台,这些操作包括部署,调度和节点集群间扩展. master node:主节点 Master 是 C ...

  9. 显示两行文字,超出显示省略号 css

    1 width: 100px; 2 background-color: pink; //一下内容为设置文字换行 及 只显示两行,超出显示省略号 3 text-overflow: -o-ellipsis ...

  10. MQTT 发布/订阅模式介绍

    MQTT 发布/订阅模式 发布订阅模式(Publish-Subscribe Pattern)是一种消息传递模式,它将发送消息的客户端(发布者)与接收消息的客户端(订阅者)解耦,使得两者不需要建立直接的 ...