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

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

posted @ 2019-08-21 14:50  1只在路上的程序猿  阅读(1833)  评论(0编辑  收藏  举报