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 ...
随机推荐
- ubuntu14.0 更改默认python为3.5 并安装tensorflow(cpu)
转:http://blog.csdn.net/qq_27657429/article/details/53482595 第一:安装pip(如果有pip 跳过) #在ubuntu/Linux 64-bi ...
- OpenCV2.4.5 加 Cuda5.0在vs2010下工
想用opencv结合gpu加速处理,想重新编译opencv结合cuda模块无奈总出错 在国外网站上搜到一个cmakelists比较靠谱,项目可以生成,但还没有测试程序把list贴出来 ######## ...
- Spring注解驱动——组件注册系列
1.@Configuration 从Spring3.0,@Configuration用于定义配置类,可替换xml配置文件,被注解的类内部包含有一个或多个被@Bean注解的方法,这些方法将会被Annot ...
- MySQL数据分析-(6)数据库设计之规范化
大家好,我是jacky,很高兴继续跟大家学习MySQL数据分析这门课,上次课我们介绍了E-R图,我们要给手机销售公司设计数据库,那么同一个项目,10个设计人员可能设计出10种不同的E-R图:因为不同的 ...
- 重读APUE(15)-pthread_cond_wait与while循环
即使pthead_cond_wait()和pthread_cond_timewait()没有错误返回,等待的条件也可能是假的:即使pthread_cond_timewait()返回了超时错误,关联的条 ...
- Linux设备驱动程序 之 工作队列
工作队列可以把工作推后,交给一个内核线程去执行–这个下半部分总是会在进程上下文中执行:通过工作队列执行的代码占尽进程上下文的优势:最重要的是工作队列允许重新调度甚至睡眠: 在工作队列和软中断/task ...
- shell中的for循环用法详解
for i in “file1” “file2” “file3”for i in /boot/*for i in /etc/*.conffor i in $(seq -w 10) –>等宽的01 ...
- linux下的什么工具可以用来查看PostScript文件?
答: ghostview,官网在这里
- [go]template使用
//index.html {{if gt .Age 18}} <p>hello, old man, {{.Name}}</p> {{else}} <p>hello, ...
- HTM概述
Html: Hyper Text Markup Language 超文本标记语言 超文本: 超出纯文本的范畴 标记语言: 标记其实就是标签 标签的格式: <标签名称>