java发起http请求调用post与get接口的方法实例
作者:GAo_ei 发布时间:2022-12-28 23:22:58
标签:http请求,get,post
一、java调用post接口
1、使用URLConnection或者HttpURLConnection
java自带的,无需下载其他jar包
URLConnection方式调用,如果接口响应码被服务端修改则无法接收到返回报文,只能当响应码正确时才能接收到返回
public static String sendPost(String url, String param) {
OutputStreamWriter out = null;
BufferedReader in = null;
StringBuilder result = new StringBuilder("");
try {
URL realUrl = new URL(url);
// 打开和URL之间的连接
URLConnection conn = realUrl.openConnection();
// 设置通用的请求属性
conn.setRequestProperty("Content-Type","application/json;charset=UTF-8");
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);
// 获取URLConnection对象对应的输出流
out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
// 发送请求参数
out.write(param);
// flush输出流的缓冲
out.flush();
// 定义BufferedReader输入流来读取URL的响应
in = new BufferedReader(new InputStreamReader(conn.getInputStream(),"UTF-8"));
String line;
while ((line = in.readLine()) != null) {
result.append(line);
}
} catch (Exception e) {
System.out.println("发送 POST 请求出现异常!"+e);
e.printStackTrace();
}
//使用finally块来关闭输出流、输入流
finally{
if(out!=null){ try { out.close(); }catch(Exception ex){} }
if(in!=null){ try { in.close(); }catch(Exception ex){} }
}
return result.toString();
}
HttpURLConnection方式调用
//ms超时毫秒,url地址,json入参
public static String httpJson(int ms,String url,String json) throws Exception{
String err = "00", line = null;
StringBuilder sb = new StringBuilder();
HttpURLConnection conn = null;
BufferedWriter out = null;
BufferedReader in = null;
try{
conn = (HttpURLConnection) (new URL(url.replaceAll("/","/"))).openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
conn.setConnectTimeout(ms);
conn.setReadTimeout(ms);
conn.setRequestProperty("Content-Type","application/json;charset=utf-8");
conn.connect();
out = new BufferedWriter(new OutputStreamWriter(conn.getOutputStream(),"utf-8"));
out.write(new String(json.getBytes(), "utf-8"));
out.flush();//发送参数
int code = conn.getResponseCode();
if (conn.getResponseCode()==200){
in = new BufferedReader(new InputStreamReader(conn.getInputStream(),"UTF-8"));
while ((line=in.readLine())!=null)
sb.append(line);
}//接收返回值
}catch(Exception ex){
err=ex.getMessage();
}
try{ if (out!=null) out.close(); }catch(Exception ex){};
try{ if (in!=null) in.close(); }catch(Exception ex){};
try{ if (conn!=null) conn.disconnect();}catch(Exception ex){}
if (!err.equals("00")) throw new Exception(err);
return sb.toString();
}
2、使用CloseableHttpClient
使用的jar包
<dependency>
<groupId>com.alibaba.csb.sdk</groupId>
<artifactId>http-client</artifactId>
<version>1.1.5.1</version>
</dependency>
public static String httpPostJson(String url,String json) throws Exception{
String data="";
CloseableHttpClient httpClient = null;
CloseableHttpResponse response = null;
try {
httpClient = HttpClients.createDefault();
HttpPost httppost = new HttpPost(url);
httppost.setHeader("Content-Type", "application/json;charset=UTF-8");
StringEntity se = new StringEntity(json,Charset.forName("UTF-8"));
se.setContentType("text/json");
se.setContentEncoding("UTF-8");
httppost.setEntity(se);
response = httpClient.execute(httppost);
int code = response.getStatusLine().getStatusCode();
System.out.println("接口响应码:"+code);
data = EntityUtils.toString(response.getEntity(), "utf-8");
EntityUtils.consume(response.getEntity());
} catch (Exception e) {
e.printStackTrace();
} finally {
if(response!=null){ try{response.close();}catch (IOException e){} }
if(httpClient!=null){ try{httpClient.close();}catch(IOException e){} }
}
return data;
}
3、使用HttpCaller
使用的jar包同第2个中的jar包。
详情可以查看阿里云总线CSB
https://help.aliyun.com/document_detail/148571.html
public static String sendPost(){
String result = "";
HttpParameters.Builder builder = HttpParameters.newBuilder();
builder.requestURL("URL") // 设置请求的URL
.api("api") // 设置服务名
.version("version") // 设置版本号
.method("post") // 设置调用方式, get/post
.accessKey("ak").secretKey("sk"); // 设置accessKey 和 设置secretKey
// 设置请求参数(json格式)
Map<String,String> param = new HashMap<String,String>();
param.put("key1","value1");
param.put("key2","value2");
//加密,没有加密则不需要encryptParam,直接用param
Map<String,String> encryptParam = new HashMap<String,String>();
encryptParam.put("key3", getData(JSON.toJSONString(param)));
ContentBody cb = new ContentBody(JSON.toJSONString(encryptParam));
builder.contentBody(cb);
try {
result = HttpCaller.invoke(builder.build());
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
//自己的加密方式
public static String getData(String data1){
return "加密后的密文";
}
二、java调用get接口
使用java自带的URLConnection
//将map型转为请求参数型
public static String getUrlData(Map<Object, Object> data) throws Exception{
StringBuffer sb = new StringBuffer();
try {
Set<Map.Entry<Object, Object>> entries = data.entrySet();
Iterator<Map.Entry<Object, Object>> iterators = entries.iterator();
while(iterators.hasNext()){
Map.Entry<Object, Object> next = iterators.next();
sb.append(next.getKey().toString().trim()).append("=").append(URLEncoder.encode(next.getValue() + "", "UTF-8").trim()).append("&");
}
sb.deleteCharAt(sb.length() - 1);
} catch (Exception e) {
sb.append(e.toString());
}
return sb.toString();
}
//strUrl截止到?,例:http://127.0.0.1:8080/api/method?
public static String httpGet(String strUrl){
Map<Object, Object> params = new HashMap<Object, Object>();
params.put("key1", "value1");
params.put("key2", "value2");
String url=strUrl + getUrlData(params);
StringBuilder result = new StringBuilder();
BufferedReader in = null;
try {
URL realUrl = new URL(url);
// 打开和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();
// 获取所有响应头字段
// 定义 BufferedReader输入流来读取URL的响应
in = new BufferedReader(new InputStreamReader(connection.getInputStream(),"UTF-8"));
String line;
while ((line = in.readLine()) != null) {
result.append(line);
}
} catch (Exception e) {
System.out.println("发送GET请求出现异常!" + e);
e.printStackTrace();
}
finally {
if (in != null){ try { in.close(); }catch(Exception e2){} }
}
return result.toString();
}
来源:https://blog.csdn.net/G_Aoei/article/details/125168460
0
投稿
猜你喜欢
- 满满的都是干货 所有插件都是在 ctrl+alt+s 里的plugins 里进行搜索安装1、CodeGl
- SSH(Secure Shell)是一套协议标准,可以用来实现两台机器之间的安全登录以及安全的数据传送,其保证数据安全的原理是非对称加密。传
- 本文实例讲述了WinForm实现状态栏跑马灯效果的方法。分享给大家供大家参考,具体如下:using System;using System.
- 1、首先说一下用法,BigDecimal中的divide主要就是用来做除法的运算。其中有这么一个方法.public BigDecimal d
- 前言作为一个新手,最近在学习C#,自己折腾弄了个简单的小说爬虫,实现了把小说内容爬下来写入txt,还只能爬指定网站。第一次搞爬虫,涉及到了网
- java中找不到符号问题 java找不到符号如果你的代码里没有报错,明明是存在的。但是java报错找不到符号。像下面这样子。解决步
- 给Word文档设置背景时,通常只能针对整篇文档设置统一的背景,如果需要对某些页面单独设置背景,则需要通过另外的方式来实现。本文通过C# 程序
- 本文实例讲述了C#控制台进行文件读写的方法。分享给大家供大家参考。具体如下:C#控制台进行文件写入:using System;using S
- 第一步:官网(或跟硬件开发WMI的人沟通你需要的接口和参数定义,如果是和硬件开发的人协定WMI接口,直接看第二步)查找你需要的WMI信息;举
- 本文实例讲述了C#实现的JS操作类。分享给大家供大家参考。具体如下:这个C#类封装了常用的JS客户端代码操作,包括弹出对话框、返回上一页,通
- 在以往的 Tomcat 项目中,一直习惯用 Ant 打包,使用 build.xml 配置,通过 ant -buildfile 的方式在机器上
- 并行和并发并行:多个CPU实例或是多台机器同时执行一段处理逻辑,是真正的同时。并发:一个CPU或一台机器,通过CPU调度算法,让用户看上去同
- 本文实例讲述了C#将布尔类型转换成字节数组的方法。分享给大家供大家参考。具体如下:byte[] b = null;b = BitConver
- 今天,给大家分享一个Java后端利用Phantomjs实现生成图片的功能,同学们使用的时候,可以参考下!PhantomJS简介首先,什么是P
- 红黑树红黑树是一种数据结构与算法课堂上常常提到但又不会细讲的树,也是技术面试中经常被问到的树,然而无论是书上还是网上的资料,通常都比较刻板难
- 1、需求在代码中经常会遇到需要把对象复制一遍,或者把属性名相同的值复制一遍。比如:public class Student {
- 此问题背景产生于近期需要上线的一个功能的埋点;主要表现就是在应用启动之后的一段时间内,内存使用一直呈现递增趋势。下图为场景复线后,本地通过
- 1 前言在前文中,已经讲述了 AOP 的后置处理器使用和方法,在本文中继续分享增强信息相关的源码,这里才是 AOP 的核心代码。2 spri
- 单例有多种的写法,本例是懒汉式单例的一种写法。在高并发环境下需要注意的是:1.单例在并发访问并调用其相应的getInstance方法的时候也
- java后端介绍今天我正式开始了一个新话题,那就是 Web。目前我主要会介绍后端。作为后端的老大哥 java,也有很多后端框架,比如大家耳熟