文档章节

Http Get、Post、Delete 、 Put 、Patch 实现方式实例

o
 osc_wws45aot
发布于 2019/08/21 14:50
字数 599
阅读 16
收藏 0

精选30+云产品,助力企业轻松上云!>>>

HTTP 各种接口请求方式实例,token为授权信息,每个平台要求不同,map种存放请求参数,key为参数名,value为参数值。

HTTP Patch 实现方式实例:

public static String sendPatch(String url, String params, String token) {
        String result = "";
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPatch httpPatch = new HttpPatch(url);
        httpPatch.setHeader("Content-type", "application/json");
        httpPatch.setHeader("Charset", "utf-8");
        httpPatch.setHeader("Accept", "application/json");
        httpPatch.setHeader("Accept-Charset", "utf-8");
        httpPatch.setHeader("Authorization", token);
        try {
            StringEntity data = new StringEntity(params, "utf-8");
            httpPatch.setEntity(data);
            HttpResponse response = httpClient.execute(httpPatch);
            HttpEntity entity = response.getEntity();
            int code = response.getStatusLine().getStatusCode();
            result = EntityUtils.toString(entity);
        } catch (Exception e) {
            result = "{\"status\":\"1\",\"error\":\"" + e.getMessage() + "\"}";
        }
        return result;
    }

HTTP Delete 实现方式实例:

public static String sendDelete(String url, Map<String, Object> param, String token) {
        String result = "";
        CloseableHttpClient httpClient = null;
        try {
            httpClient = getHttpClient(url);
            HttpDelete httpDelete = new HttpDelete(url);
            setRequestConfig(httpDelete);
            httpDelete.addHeader("User-Agent", DefaultUserAgent);
            //param.forEach((k, v) -> httpDelete.addHeader(k, com.alibaba.fastjson.JSONObject.toJSONString(v)));
            httpDelete.setHeader("Authorization", "Bearer " + token);
            HttpResponse httpResponse = httpClient.execute(httpDelete, HttpClientContext.create());
            HttpEntity resEntity = httpResponse.getEntity();
            if (null == resEntity) {
                result = "{\"status\":\"0\",\"error\":\"success\"}";
            } else {
                result = EntityUtils.toString(resEntity);
            }
        } catch (Exception e) {
            result = "{\"status\":\"1\",\"error\":\"" + e.getMessage() + "\"}";
        }
        return result;
    }

Http Put  实现方法实例:

public static String sendPut(String urlPath, Map<String, Object> param, String token) {
        String result = null;
        URL url = null;
        HttpURLConnection httpurlconnection = null;
        try {
            url = new URL(urlPath);
            httpurlconnection = (HttpURLConnection) url.openConnection();
            httpurlconnection.setRequestProperty("Authorization", "Bearer " + token);

            httpurlconnection.setRequestMethod("PUT");
            httpurlconnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            httpurlconnection.getOutputStream().write(com.alibaba.fastjson.JSONObject.toJSONString(param).getBytes("UTF-8"));
            httpurlconnection.getOutputStream().flush();
            httpurlconnection.getOutputStream().close();
            int code = httpurlconnection.getResponseCode();
            if (code == 200) {
                DataInputStream in = new DataInputStream(httpurlconnection.getInputStream());
                int len = in.available();
                byte[] by = new byte[len];
                in.readFully(by);
                result = new String(by, Charset.forName("UTF-8"));
                in.close();
            } else if (code == 204) {
                result = "{\"code\":0,\"message\":\"success\"}";
            } else if (code == 202) {
                result = "{\"code\":0,\"message\":\"success\"}";
            } else {
                DataInputStream in = new DataInputStream(httpurlconnection.getErrorStream());
                int len = in.available();
                byte[] by = new byte[len];
                in.readFully(by);
                result = new String(by, Charset.forName("UTF-8"));
                in.close();

            }
        } catch (Exception e) {
            result = "{\"status\":\"1\",\"error\":\"" + e.getMessage() + "\"}";
        } finally {
            url = null;
            if (httpurlconnection != null) {
                httpurlconnection.disconnect();
            }
        }
        return result;
    }

HTTP Get 实现方法实例:

public static String sendGet(String url, Map<String, Object> params, String token) {
        String result = "";
        int err = 0;
        while (true) {
            params.put("access_token", token);
            CloseableHttpClient httpClient = HttpClients.createDefault();
            try {
                List<NameValuePair> parameters = new ArrayList<NameValuePair>();
                for (Map.Entry<String, Object> entry : params.entrySet()) {
                    parameters.add(new BasicNameValuePair(entry.getKey(), entry.getValue().toString()));
                }
                HttpGet httpGet = new HttpGet(url);
                StringBuilder dataparm = new StringBuilder();
                params.forEach((k, v) -> dataparm.append("&" + k + "=" + v));
                String urlparm = "";
                String string = dataparm.toString();
                if (!"".equals(string)) {
                    urlparm = dataparm.toString().substring(1);
                }
                HttpGet httpget = new HttpGet(url + "?" + urlparm);
                setRequestConfig(httpget);
                httpget.addHeader("User-Agent", DefaultUserAgent);
                httpget.addHeader("Content-Type", "application/json");
                HttpResponse httpResponse = httpClient.execute(httpget, HttpClientContext.create());

                HttpEntity resEntity = httpResponse.getEntity();
                result = EntityUtils.toString(resEntity);
                return result;
            } catch (IOException e) {
                result = "{\"status\":\"1\",\"errors\":\"" + e.getMessage() + "\"}";
                if (err++ > 2) {
                    break;
                }
                try {
                    Thread.sleep((err + 2) * 1000);
                } catch (InterruptedException e1) {
                    result = "{\"status\":\"1\",\"errors\":\"" + e1.getMessage() + "\"}";
                }

            }
        }
        return result;
    }

HTTP Post 实现方式实例:

public static String sendPost(String url, Map<String, Object> params, String token) {
        String result = "";
        int err = 0;
        while (true) {
            params.put("access_token", token);
            CloseableHttpClient client = HttpClients.createDefault();
            HttpPost httpPost = new HttpPost(url);
            try {
                httpPost.addHeader("Content-Type", "application/json");
                httpPost.setEntity(new ByteArrayEntity(com.alibaba.fastjson.JSONObject.toJSONString(params).getBytes("UTF-8")));
                HttpResponse httpResponse = client.execute(httpPost, HttpClientContext.create());
                HttpEntity resEntity = httpResponse.getEntity();
                result = EntityUtils.toString(resEntity);
                return result;
            } catch (IOException e) {
                result = "{\"status\":\"1\",\"errors\":\"" + e.getMessage() + "\"}";
                if (err++ > 2) {
                    break;
                }
                try {
                    Thread.sleep((err + 2) * 1000);
                } catch (InterruptedException e1) {
                    result = "{\"status\":\"1\",\"errors\":\"" + e1.getMessage() + "\"}";
                }

            }
        }
        return result;
    }

 

 

原文链接:https://blog.csdn.net/mi_gu_niang/article/details/89396812

o
粉丝 0
博文 500
码字总数 0
作品 0
私信 提问
加载中
请先登录后再评论。
vue-resource中文文档

Vue可以构建一个完全不依赖后端服务的应用,同时也可以与服务端进行数据交互来同步界面的动态更新。 Vue通过插件的形式实现了基于AJAX,JSPNP等技术的服务端通信。 是一个通过或技术实现异步...

osc_b7xn6aes
2018/10/12
2
0
axios 源码分析(上) 使用方法

axios是一个基于Promise 用于浏览器和 nodejs 的 HTTP 客户端,它可以在浏览器和node环境下运行,在github上已经有六七万个星了,axios使用很方便,很多人在使用他,vue官方也推荐使用axios了...

osc_2snvc4af
2019/09/29
5
0
为什么要用Put/Delete接口:Restful API简介

前言 最近发现小伙伴们写的API不仅仅有Get/Post,还有大量的Put/Patch/Delete,其实是有点疑惑的:所有的这些操作使用Post不就都能搞定吗?事实确实如此,Post能够搞定一切的需求。那为什么还...

脚丫先生
03/31
0
0
理解RESTful API

近日妹子向我求助RESTful API到底是个什么东西。原因是她们公司一个新启动的项目因为RESTful API起了争执。服务端同学坚持要用RESTful API,而前端同学则认为服务端用RESTful API就会让前端的...

老於`
04/27
0
0
理解RESTful API

近日妹子向我求助RESTful API到底是个什么东西。原因是她们公司一个新启动的项目因为RESTful API起了争执。服务端同学坚持要用RESTful API,而前端同学则认为服务端用RESTful API就会让前端的...

老於`
04/27
0
0

没有更多内容

加载失败,请刷新页面

加载更多

等到所有jQuery Ajax请求都完成了吗? - Wait until all jQuery Ajax requests are done?

问题: How do I make a function wait until all jQuery Ajax requests are done inside another function? 我如何让一个函数等到所有jQuery Ajax请求都在另一个函数中完成之后? In short...

富含淀粉
23分钟前
17
0
OSChina 周日乱弹 —— 那么长的绳子,你这是放风筝呢

Osc乱弹歌单(2020)请戳(这里) 【今日歌曲】 @ 巴拉迪维:黑豹乐队的单曲《无地自容》 耳畔突然响起旋律,是那首老歌。中国摇滚有了《一无所有》不再一无所有;中国摇滚有了《无地自容》不...

小小编辑
今天
65
1
《吐血整理》-顶级程序员书单集

你知道的越多,你不知道的越多 给岁月以文明,而不是给文明以岁月 前言 王潇:格局决定了一个人的梦想,梦想反过来决定行为。 那格局是什么呢? 格局是你能够看见的深度、广度和密度。 王潇认...

敖丙
2019/12/11
15
0
我可以在Android版式中加下划线吗? - Can I underline text in an Android layout?

问题: 如何在Android布局xml文件中定义带下划线的文本? 解决方案: 参考一: https://stackoom.com/question/A31z/我可以在Android版式中加下划线吗 参考二: https://oldbug.net/q/A31z/...

法国红酒甜
今天
26
0
干掉ELK | 使用Prometheus+Grafana搭建监控平台

什么是Prometheus? Prometheus是由SoundCloud开发的开源监控报警系统和时序列数据库(TSDB)。Prometheus使用Go语言开发,是Google BorgMon监控系统的开源版本。 Prometheus的特点 · 多维度...

木九天
今天
34
0

没有更多内容

加载失败,请刷新页面

加载更多

返回顶部
顶部