首页 > 其他分享 >封装HttpUtils类,根据实际业务返回值 封装JsonRootBean 对象

封装HttpUtils类,根据实际业务返回值 封装JsonRootBean 对象

时间:2023-01-05 19:13:04浏览次数:45  
标签:map 封装 String HttpUtils JsonRootBean http put import public

package com.tf.jcfx.util;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hc.client5.http.classic.methods.HttpPost;
import org.apache.hc.client5.http.config.RequestConfig;
import org.apache.hc.client5.http.entity.UrlEncodedFormEntity;
import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.core5.http.ContentType;
import org.apache.hc.core5.http.HttpEntity;
import org.apache.hc.core5.http.HttpStatus;
import org.apache.hc.core5.http.NameValuePair;
import org.apache.hc.core5.http.io.entity.EntityUtils;
import org.apache.hc.core5.http.io.entity.StringEntity;
import org.apache.hc.core5.http.message.BasicNameValuePair;
import com.google.gson.Gson;
import com.tf.jcfx.vo.util.JsonRootBean;

public class HttpUtils {
private static final Log log = LogFactory.getLog(HttpUtils.class);

/**
* post请求
*
* @param url
* @param param
* @return
* @throws Exception
*/
public static String httpPost(String url, Map<String, Object> map) throws Exception {
String result = null;
try {
HttpPost post = new HttpPost(url);
//requestConfig post请求配置类,设置超时时间
RequestConfig requestConfig = RequestConfig.custom().build();
post.setConfig(requestConfig);
List<NameValuePair> params = new ArrayList<NameValuePair>();
for (Map.Entry<String, Object> entry : map.entrySet()) {
if (entry.getValue() != null && entry.getValue() != "") {
params.add(new BasicNameValuePair(entry.getKey(), entry.getValue() + ""));
}
}
//在这个地方设置编码 防止请求乱码
post.setEntity(new UrlEncodedFormEntity(params));
CloseableHttpResponse httpResponse = HttpClients.createDefault().execute(post);
System.out.println("返回数据:" + httpResponse);
HttpEntity httpEntity = httpResponse.getEntity();
result = EntityUtils.toString(httpEntity);// 取出应答字符串


} catch (Exception e) {
throw e;
}
return result;
}

public static String doPost(String url, String json) throws Exception {
HttpPost post = new HttpPost(url);

try {
StringEntity s = new StringEntity(json, ContentType.APPLICATION_JSON, "UTF-8", false); // 中文乱码在此解决
post.setEntity(s);
CloseableHttpResponse res = HttpClients.createDefault().execute(post);
if (res.getCode() == HttpStatus.SC_OK) {
String result = EntityUtils.toString(res.getEntity());// 返回json格式:
return result;
}
} catch (Exception e) {
throw e;
}
return null;
}



public static String SendMessage(String userCode,String message,String title,String description,String module,String moduleParam) {
String httpPost="";
try {
Map<String, Object> map=new HashMap<String, Object>();
map.put("systemToken",getMesssageToken());
map.put("messageCode",AssitUtil.getMemoryPiece("messageCode").toString());
map.put("userCode",userCode);
map.put("title",title);
map.put("description",description);
map.put("content",message);
map.put("module",module);
map.put("moduleParam",moduleParam);
httpPost = HttpUtils.doPost(AssitUtil.getMemoryPiece("sendMessageUrl").toString(), new Gson().toJson(map));

}catch(Exception e){
log.error("推送失败!");
e.printStackTrace();
}
return httpPost;
}

public static String getMesssageToken() throws Exception {
String doPost = HttpUtils.doPost(AssitUtil.getMemoryPiece("messsageTokenUrl").toString(), "");
Gson gson = new Gson();
JsonRootBean bean = gson.fromJson(doPost,JsonRootBean.class);

return bean.getData().getToken();
}

public static void main(String[] args) throws Exception {

/* Map<String, Object> map=new HashMap();

map.put("systemToken","8ee937427e344bed80639751edf9832d");
map.put("messageCode","02ae61c9883c4cfdb5fba1122179c0b6");
map.put("userCode","17461");
map.put("title","文件");
map.put("description","文件");
map.put("content","文件");
map.put("module","sto.com.shtb.native.mobile.datacenter");
map.put("moduleParam","打的");
String json =new Gson().toJson(map);
String httpPost = HttpUtils.doPost("http://10.10.14.146/api/message-center/pc/message_center/v2/push", json);*/
/* String insertMessage = SendMessage("17461","该吃饭了");
if (!insertMessage.contains("\"result\":\"0\"")) {
log.warn(" " + insertMessage);
}
System.out.println(insertMessage);*/
/* String doPost = HttpUtils.doPost("http://10.10.14.146/api/auth-server/pc/com/token?comId=02ab648587494f62bf563fd20a607e7d", "");
System.out.println(doPost);

Gson gson = new Gson();

JsonRootBean bean = gson.fromJson(doPost,JsonRootBean.class);
System.out.println(bean.getData().getToken());*/

}

}

 

 

JsonRootBean 对象

 

package com.tf.jcfx.vo.util;

/**
* Copyright 2022 json.cn
*/


/**
* Auto-generated: 2022-10-30 10:15:18
*
* @author json.cn ([email protected])
* @website http://www.json.cn/java2pojo/
*/
public class JsonRootBean {

private String result;
private String message;
private Data data;
private String totalCount;
private String expMessage;
public void setResult(String result) {
this.result = result;
}
public String getResult() {
return result;
}

public void setMessage(String message) {
this.message = message;
}
public String getMessage() {
return message;
}

public void setData(Data data) {
this.data = data;
}
public Data getData() {
return data;
}

public void setTotalCount(String totalCount) {
this.totalCount = totalCount;
}
public String getTotalCount() {
return totalCount;
}

public void setExpMessage(String expMessage) {
this.expMessage = expMessage;
}
public String getExpMessage() {
return expMessage;
}

}

 

标签:map,封装,String,HttpUtils,JsonRootBean,http,put,import,public
From: https://www.cnblogs.com/zhil/p/17028647.html

相关文章

  • python cron croniter优化封装标准-支持秒级 , ?
    一、基本方法,用python得知cron表达式"""计算定时任务下次运行时间schedstr:定时任务时间表达式timeFormatstr:格式为"%Y-%m-%d%H:%M"queryTimesint:查询下次运行次......
  • python接口自动化系列 - openpyxl库封装04
    前言为了更好的让openpyxl在工作中使用,将openpyxl的常用操作封装起来,这样不仅复用性高,而且阅读性好fromopenpyxlimportload_workbookfromopenpyxl.stylesimportP......
  • 基于vue+Element Table 表格的封装
    项目场景:项目场景:需要频繁使用列表进行呈现数据,不可能每次都写一个表格,可以将表格封装为一个组件,在需要使用时可以直接调用。效果展示:项目结构:具体实现:Table.vue......
  • 多项式半家桶~式子+未封装代码~
    式子多项式乘法逆已知\(F(x)G(x)\equiv1\;\;(mod\;x^n)\),\(F(x)H(x)\equiv1\;\;(mod\;x^{\lceil\frac{n}{2}\rceil})\),则\[G(x)\equiv2H(x)-F(x)H^2(x)\;\;(mod\;x^......
  • 简单封装Poly
    非常优雅的马蜂#include<bits/stdc++.h>typedeflonglongll;typedefunsignedlonglongull;typedefdoubledb;typedeflongdoubleldb;#definefre(x)freopen(......
  • 多项式封装
    推销一下基于继承的多项式封装,好多函数可以直接用vector的,不用再次封装了,省事很多另外()运算符太赞了,虽然时间是resize()的\(4\)倍,但是很好用!!,再也不用费力计算多项式的大......
  • winform中的提示框+MSN提示封装,原生的也不错
    开发winform项目时,如果某个功能执行完成,需要告诉用户结果,比如成功还是失败?可以用提示框实现,今天就来聊聊这个不太起眼的小功能:提示框。其实net提供的提示框已经很丰富了,如......
  • Cadence Allegro贴片和插件元器件封装制作流程总结
    目录​​1.0805电阻封装的制作​​​​1.1计算焊盘尺寸​​​​1.2制作焊盘(用于生成*.pad)​​​​1.2封装制作(生成*.dra)​​​​1.3设置参数、栅格grid和原点​​​......
  • Java【封装一个新闻类,包含标题和内容属性】
    题目:1、封装一个新闻类,包含标题和内容属性,提供get、set方法,重写toString方法,打印对象时只打印标题;(10分)2、只提供一个带参数的构造器,实例化对象时,只初始化标题;并且实例化......
  • 软件开发入门教程网 之​​数据封装
    所有的C++程序都有以下两个基本要素:**程序语句(代码):**这是程序中执行动作的部分,它们被称为函数。**程序数据:**数据是程序的信息,会受到程序函数的影响。封装是面向对象编程......