
Java后台对接第三方接口发送数据GET\POST\PUT\SOCKET
发布日期:2021-05-07 22:42:01
浏览次数:22
分类:精选文章
本文共 7213 字,大约阅读时间需要 24 分钟。
Java后台对接第三方接口发送数据GET\POST\PUT\SOCKET
工具类
//GET///** * get请求 * * @param url 目标地址 * @param param 参数 * @return String 响应信息 */ 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(); // 定义 BufferedReader读取URL的响应 in = new BufferedReader(new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8)); String line; while ((line = in.readLine()) != null) { result += line; } } catch (Exception e) { log.error("GET请求异常{}" , e.getMessage()); } finally { try { if (in != null) { in.close(); } } catch (Exception e2) { e2.getMessage(); } } return result; }////////////////////////////////POST/////////////////////////// /** * 向指定 URL 发送POST方法的请求 * * @param url 发送请求的 URL * @param param 请求参数,json * @return 响应结果 */ public static String sendPost(String url, String param) { OutputStreamWriter out = null; BufferedReader in = null; String result = ""; //创建连接 try { URL httpUrl = null; //HTTP URL类 用这个类来创建连接 //创建URL httpUrl = new URL(url); //建立连接 HttpURLConnection conn = (HttpURLConnection) httpUrl.openConnection(); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "application/json"); conn.setRequestProperty("connection", "keep-alive"); conn.setUseCaches(false);//缓存关闭 conn.setInstanceFollowRedirects(true); conn.setDoOutput(true); conn.setDoInput(true); conn.connect(); //POST请求 out = new OutputStreamWriter(conn.getOutputStream()); out.write(param); out.flush(); //读取响应 in = new BufferedReader(new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8)); String line; while ((line = in.readLine()) != null) { result += line; } in.close(); // 断开连接 conn.disconnect(); } catch (Exception e) { log.error("发送 POST 请求出现异常!{}" , e.getMessage()); } //使用finally块来关闭输出流、输入流 finally { try { if (out != null) { out.close(); } if (in != null) { in.close(); } } catch (IOException ex) { ex.getMessage(); } } return result; }///PUT/ /** * put请求 * * @param url 目标地址 * @param map 参数 * @return String响应结果 */ public static String sendPut(String url, Map map) { String encode = "utf-8"; CloseableHttpClient closeableHttpClient = HttpClients.createDefault(); HttpPut httpput = new HttpPut(url); httpput.setHeader("Accept", "*/*"); httpput.setHeader("Accept-Encoding", "gzip, deflate"); httpput.setHeader("Cache-Control", "no-cache"); httpput.setHeader("Connection", "keep-alive"); httpput.setHeader("Content-Type", "application/json;charset=UTF-8"); //请求参数处理 StringEntity stringEntity = new StringEntity(JSON.toJSONString(map), encode); httpput.setEntity(stringEntity); String content = null; CloseableHttpResponse httpResponse = null; try { //响应信息 httpResponse = closeableHttpClient.execute(httpput); HttpEntity entity = httpResponse.getEntity(); content = EntityUtils.toString(entity, encode); } catch (Exception e) { e.printStackTrace(); } finally { try { httpResponse.close(); } catch (IOException e) { e.getMessage(); } } try { closeableHttpClient.close(); //关闭连接、释放资源 } catch (IOException e) { e.getMessage(); } return content; }/////////////////////////////socket//////////////////////// /** * socket发送数据 * * @param text 数据 * @param host 地址 * @param port 端口 */ public static void forwardSocket(String text, String host, Integer port) { Socket socket = null; OutputStream outputStream = null; DataOutputStream dataOutputStream = null; try { socket = new Socket(host, port); outputStream = socket.getOutputStream(); //把输出流封装在DataOutputStream中 dataOutputStream = new DataOutputStream(outputStream); //使用writeUTF发送字符串 dataOutputStream.writeUTF(text); dataOutputStream.close(); socket.close(); } catch (IOException e) { log.error("socket发送数据-失败{}", e.getMessage()); } finally { try { if (dataOutputStream != null) { dataOutputStream.close(); } if (socket != null) { socket.close(); } } catch (Exception ex) { log.error("error to socket close :{}", ex.getMessage()); } } }
使用案例
get就不多说了
post请求/** * 上传信息 */ @RequestMapping(value = "/uploadEmp", method = RequestMethod.POST) @ResponseBody public JsonData uploadData(Demo emp) { int code = 1; String message = ""; try { String result = GetPostPutUtil.sendPost("http://xxx:1012/api/demo", JSON.toJSONString(emp));//实体类对象json化,alibaba.fastjson //获取响应状态 boolean contains1 = result.contains("\"code\":"); if (contains1) { code = Integer.parseInt(result.split("\"code\":")[1].split(",", 0)[0]); } //获取响应信息 boolean contains2 = result.contains("\"message\":\""); if (contains2) { message = result.split("\"message\":\"")[1].split("\"}", 0)[0]; } ///省略// } 响应结果:{ "code":0,"message":"上传成功"}
PUT请求
/** * 删除 * * @return String */ @RequestMapping(value = "/deleteDemo") @ResponseBody public String deleteDemo() { Listid = new ArrayList(); id.add("000012"); HashMap map = new HashMap (); map.put("demoName", "张三"); map.put("id", id); return GetPostPutUtil.sendPut("http://xxxx:1012/api/delete", map); } 响应结果:{ "code":0,"message":"删除成功"}
发表评论
最新留言
能坚持,总会有不一样的收获!
[***.219.124.196]2025年04月11日 10时19分26秒
关于作者

喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!
推荐文章
QWaitCondition把异步调用封装成同步调用
2021-05-08
windows驱动开发-编译错误集合
2021-05-08
嵌入式linux系统应用开发
2021-05-08
Linux驱动开发之PCIe Host驱动
2021-05-08
Vue.js Element Basic组件使用
2021-05-08
android MVP模式
2021-05-08
基本vi命令使用
2021-05-08
android 头像选择,裁剪全套解决方案,你值得拥有!
2021-05-08
MapReduce
2021-05-08
springboot swagger2
2021-05-08
shell(十)case的几个典型应用
2021-05-08
Linux环境变量配置错误导致命令不能使用(杂谈)
2021-05-08
openstack安装(六)镜像glance服务安装
2021-05-08
openstack安装(九)网络服务的安装--控制节点
2021-05-08
shell编程(六)语言编码规范之(变量)
2021-05-08
linux杂谈之特殊字符的打印和在各种软件如何打出
2021-05-08
vim杂谈(三)之配色方案
2021-05-08
vim杂谈(五)之vim不加载~/.vimrc
2021-05-08
Linux杂谈之终端快捷键
2021-05-08
vimscript学习笔记(二)预备知识
2021-05-08