java 自带 http get/post 请求
请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.Map;
import java.util.Set; public class HttpRequest {
/**
* 向指定URL发送GET方法的请求
*
* @param url 发送请求的URL
* @param param 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
* @return URL 所代表远程资源的响应结果
*/
public static String sendGet(String url, String param) {
String result = "";
BufferedReader in = null;
try {
String urlNameString = url + "?" + param;
URL realUrl = new URL(urlNameString);
// 打开和URL之间的连接
URLConnection connection = realUrl.openConnection();
// 设置通用的请求属性
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.connect();
// 获取所有响应头字段
Map<String, List<String>> map = connection.getHeaderFields();
// 遍历所有的响应头字段
for (String key : map.keySet()) {
System.out.println(key + "--->" + map.get(key));
}
// 定义 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);
e.printStackTrace();
}
// 使用finally块来关闭输入流
finally {
try {
if (in != null) {
in.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
return result;
} /**
* 向指定 URL 发送POST方法的请求
*
* @param url 发送请求的 URL
* @param map/param 请求参数
*
* 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
* @return 所代表远程资源的响应结果
*/
public static String sendPost(String url, String param) {
// public static String sendPost(String url, Map<String, String> map) {
// String param = getKeyVAlueSting(map); //如果是参数是String 就不需要再转换成name1=value1&name2=value2 的形式
System.out.println(param);
PrintWriter out = null;
BufferedReader in = null;
String result = "";
try {
URL realUrl = new URL(url);
// 打开和URL之间的连接
URLConnection conn = realUrl.openConnection();
// 设置通用的请求属性
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
// 发送POST请求必须设置如下两行
conn.setDoOutput(true);
conn.setDoInput(true);
// 1.获取URLConnection对象对应的输出流
out = new PrintWriter(conn.getOutputStream());
// 2.中文有乱码的需要将PrintWriter改为如下
// out=new OutputStreamWriter(conn.getOutputStream(),"UTF-8")
// 发送请求参数
out.print(param);
// flush输出流的缓冲
out.flush();
// 定义BufferedReader输入流来读取URL的响应
in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
System.out.println("发送 POST 请求出现异常!" + e);
e.printStackTrace();
}
// 使用finally块来关闭输出流、输入流
finally {
try {
if (out != null) {
out.close();
}
if (in != null) {
in.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
return result;
} /**
* 获取key=value格式字符串
*
* @param map
* @return
*/
public static String getKeyVAlueSting(Map<String, String> map) {
String sign = ""; Set<String> set = map.keySet();
for (String key : set) {
sign += key + "=" + map.get(key) + "&";
} sign = sign.substring(0, sign.length() - 1); return sign;
} public static void main(String[] args) {
HttpRequest httpRequest = new HttpRequest(); //测试微信项目中通过post请求获取access token
String url = "https://api.weixin.qq.com/cgi-bin/token";
String param = "grant_type=client_credential&appid=wxfc27805daac56d9b&secret=12d853529003c68d0d2c9d4f87dd8b57";
String sr=HttpRequest.sendPost(url, param);
System.out.println(sr);
}
}
Json格式、Post请求:
/**Map转json post请求*/
public void a(){
Map<String, String> map = new LinkedHashMap<>();
map.put("type",type)
Map<String, String> requestMap = new LinkedHashMap<>();
requestMap.put("bg_url", bg_url);
requestMap.put("biz_code", biz_code);
requestMap.put("sign", sign);
map.put("data",requestMap);
// 组装请求参数,JSON格式
JSONObject json = new JSONObject(map); String result=sendPostJson("请求地址url",json.toJSONString());
} /**
* Post请求、 Json格式
* @param strURL
* @param params
* @return
*/
public static String sendPostJson(String strURL, String params) {
BufferedReader reader = null;
try {
URL url = new URL(strURL);// 创建连接
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setUseCaches(false);
connection.setInstanceFollowRedirects(true);
connection.setRequestMethod("POST"); // 设置请求方式
connection.setRequestProperty("Content-Type", "application/json"); // 设置发送数据的格式
connection.connect();
OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream(), "UTF-8"); // utf-8编码
out.append(params);
out.flush();
out.close();
// 读取响应
reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
String line;
String res = "";
while ((line = reader.readLine()) != null) {
res += line;
}
reader.close();
return res;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return ""; // 自定义错误信息
}
java 自带 http get/post 请求的更多相关文章
- java自带的http get/post请求servlet
http请求方式太多,有java自带的,也有httpClient,用的地方还挺多,所以在此做一个小小的总结: public class HttpRequest { /** * 向指定URL发送GET方 ...
- 深入理解Java自带的线程池和缓冲队列
前言 线程池是什么 线程池的概念是初始化线程池时在池中创建空闲的线程,一但有工作任务,可直接使用线程池中的线程进行执行工作任务,任务执行完成后又返回线程池中成为空闲线程.使用线程池可以减少线程的创建和 ...
- 测试框架httpclent 3.获取cookie的信息,然后带cookies去发送请求
在properties文件里面: startupWithCookies.json [ { "description":"这是一个会返回cookies信息的get请求&qu ...
- java中两种发起POST请求,并接收返回的响应内容的方式 (转)
http://xyz168000.blog.163.com/blog/static/21032308201162293625569/ 2.利用java自带的java.net.*包下提供的工具类 代码如 ...
- 如何在java中发起http和https请求
一般调用外部接口会需要用到http和https请求. 一.发起http请求 1.写http请求方法 //处理http请求 requestUrl为请求地址 requestMethod请求方式,值为&qu ...
- Java基础/发起http和https请求
Java中发起http和https请求 一般调用外部接口会需要用到http和https请求. 本案例为:前后端完全分离,前端框架(React+Mobx+Nornj),后端(Go语言). 面临问题:跨域 ...
- 常用java自带命令概览
ref:http://www.hollischuang.com/archives/308 一.常用命令 jps: 查看本机的Java中进程信息. jstack: 打印线程的执行栈信息. jmap: 打 ...
- JAVA实现带图片的列表——JList
JList:显示对象列表并且允许用户选择一个或多个项的组件. JList的构造方法: 1.根据数组创建列表: JList(Object[] listData) 构造一个 JList,使其显示指定数组中 ...
- java自带工具-jps、jinfo、jstack、jstat、jmap
掌握java自带的这些监控工具,有助与我们很好的分析问题和jvm性能调优秀.收集了些网上整理很好的文章. Java监控工具.调优.调试辅助函数 Java自带的GUI性能监控工具Jconsole以及Ji ...
随机推荐
- python 安装 pyHook
下载网站:https://www.lfd.uci.edu/~gohlke/pythonlibs/#pyhook 查看python版本 C:\Users\k\Desktop\file_trans> ...
- Flask 四种响应类型
1 直接返回字符串 可以返回状态码 @app.route('/testresponse', methods=['GET', 'POST']) def testresponse(): return &q ...
- CentOS7.4中配置jdk环境
参考:https://www.linuxidc.com/Linux/2016-09/135556.htm 1.下载jdk 首先创建安装包放置位置 mkdir -p /usr/local/java 然后 ...
- np.random.choices的使用
在看莫烦python的RL源码时,他的DDPG记忆库Memory的实现是这样写的: class Memory(object): def __init__(self, capacity, dims): ...
- Cesium中级教程6 - 3D Models 三维模型
3D Models 三维模型 本教程将教您如何通过Primitive API转换.加载和使用Cesium中的三维模型.如果你是Cesium的新用户,可能需要阅读三维模型部分的(空间数据可视化教程)[h ...
- mysql端口3306无法访问
mysql主备复制,show slave status显示IO一直connecting 一.查看了防火墙,已经处于关闭状态 二.查看使用的复制用户的权限,也已经开放 三.telnet访问另外一台机器端 ...
- 转载:OutOfMemoryError系列(2): GC overhead limit exceeded
这是本系列的第二篇文章, 相关文章列表: OutOfMemoryError系列(1): Java heap space OutOfMemoryError系列(2): GC overhead limit ...
- mod 运算与乘法逆元
mod 运算与乘法逆元 %运算 边乘边mod 乘法 除法 mod 希望计算5/2%7=6 乘法 除法 mod 希望计算5/2%7=6 两边同时/x 在取mod(p)运算下,a/b=a*bp-2 bp- ...
- hadoop查看文件大小
hadoop fs -du /yj/input/ 列出input下所有文件的大小,以B为单位 #!/bin/sh #echo "hadoop fs -du /" hadoop fs ...
- leetcode 79. Word Search 、212. Word Search II
https://www.cnblogs.com/grandyang/p/4332313.html 在一个矩阵中能不能找到string的一条路径 这个题使用的是dfs.但这个题与number of is ...