java发起http请求调用post与get接口的方法实例
作者:GAo_ei 时间:2022-12-28 23:22:58
一、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
标签:http请求,get,post
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
springboot整合@Retryable实现重试功能的示例代码
2023-11-27 11:08:20
spring security自定义登录页面
2022-06-11 14:03:04
![](https://img.aspxhome.com/file/2023/5/86725_0s.jpg)
Java求1+2!+3!+...+20!的和的代码
2021-12-16 10:55:23
Java数据结构之线段树的原理与实现
2021-12-17 13:30:52
![](https://img.aspxhome.com/file/2023/8/72608_0s.png)
Android中利用SurfaceView制作抽奖转盘的全流程攻略
2022-02-04 00:43:10
![](https://img.aspxhome.com/file/2023/6/137416_0s.gif)
Javaweb获取表单数据的多种方式
2022-12-25 18:13:41
19款Javascript富文本网页编辑器
2021-12-08 23:48:45
![](https://img.aspxhome.com/file/2023/3/70623_0s.jpg)
Android中Window的管理深入讲解
2022-03-18 17:48:28
Android编程之SMS读取短信并保存到SQLite的方法
2022-01-30 18:02:45
![](https://img.aspxhome.com/file/2023/3/139003_0s.png)
Android mvvm之LiveData原理案例详解
2023-09-29 11:49:26
![](https://img.aspxhome.com/file/2023/5/92625_0s.png)
Spring Cloud Gateway集成Sentinel流控详情
2023-11-09 20:27:31
![](https://img.aspxhome.com/file/2023/2/86812_0s.png)
Java调用Zookeeper的实现步骤
2022-04-14 17:01:11
java实现微信红包 拼手气红包
2023-09-28 10:31:45
![](https://img.aspxhome.com/file/2023/3/67113_0s.jpg)
Java中Collection、List、Set、Map之间的关系总结
2022-11-18 21:41:42
java 动态 代理的方法总结
2023-08-25 04:00:33
解答为什么 Java 线程没有Running状态
2021-08-25 13:10:33
![](https://img.aspxhome.com/file/2023/2/72372_0s.jpg)
java编程常用技术(推荐)
2023-11-06 09:03:44
![](https://img.aspxhome.com/file/2023/1/132081_0s.png)
Android MaterialCardView的使用介绍与示例
2023-06-23 06:31:56
![](https://img.aspxhome.com/file/2023/2/138692_0s.jpg)
利用Spring Data MongoDB持久化文档数据的方法教程
2023-05-05 02:36:54
C#实现下载网页HTML源码的方法
2023-06-10 01:07:24