通过get、post、put、delete链接java的http接口

运用场景说明

在平时做项目中不敢说经常,但是应该会遇到需要连接别人的接口获取数据的一些问题,特别是多个部门联合开发的时候,我平时也遇到了一些,而且有的感觉很有意思,所以本次记录下来!本次是一个util类可以直接用,话不多说,直接先上代码(注:本人是java开发,开发工具idea)

// An highlighted block
package com.server.common.util;

import com.alibaba.fastjson.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.Map;

public class GetPostUtil {

    /**
     * post请求
     */
    public static String sendPost(String url, String param) {
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            // 链接URL
            URLConnection conn = realUrl.openConnection();
            // 设置请求属性
            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 PrintWriter(conn.getOutputStream());
            // 发送请求参数
            out.print(param);
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("发送 POST 请求出现异常:" + e);
            e.printStackTrace();
        }
        //关闭输出流、输入流
        finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return result;
    }

    /**
     * GET方法
     */
    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();

            HttpURLConnection httpURLConnection = (HttpURLConnection) connection;
            httpURLConnection.setRequestMethod("GET");// 提交模式
            // 设置请求属性
            httpURLConnection.setRequestProperty("accept", "*/*");
            httpURLConnection.setRequestProperty("connection", "Keep-Alive");
            httpURLConnection.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 建立实际的连接
            httpURLConnection.connect();
            // 获取所有响应头字段
            Map<String, List<String>> map = httpURLConnection.getHeaderFields();
            // 遍历所有的响应头字段
            for (String key : map.keySet()) {
//                System.out.println(key + "--->" + map.get(key));
//                result +=key;
            }
            // 定义 BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(
                    connection.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("发送GET请求出现异常:" + e);
            e.printStackTrace();
        }
        // 关闭输入流
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return result;
    }

    /**
     * 发送Put或者Delete方法的请求
     */
    public static String sendDelete(String url, String param) {
        String result = "";
        BufferedReader in = null;
        try {
            String urlNameString = url + "?" + param;
            URL realUrl = new URL(urlNameString);
            // 链接URL
            HttpURLConnection connection = (HttpURLConnection) 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.setRequestMethod("DELETE");
//            connection.setRequestProperty("timestamp", timestamp);
//            connection.setRequestProperty("CompanyCode", CompanyCode);
//            connection.setRequestProperty("companyPassword", companyPassword);
            // 建立实际的连接
            connection.connect();
            // 获取所有响应头字段
            Map<String, List<String>> map = connection.getHeaderFields();
            // 遍历所有的响应头字段
            for (String key : map.keySet()) {
                System.out.println(key + "--->" + map.get(key));
                result += key;
            }
            // 定义 BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(
                    connection.getInputStream(), "utf-8"));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("发送DELETE请求出现异常:" + e);
            e.printStackTrace();
        }
        // 关闭输入流
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return result;
    }

    /**
     * post请求(header带参数)
     */
    public static String sendPostHeader(String url, String param, String bearer) {
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            // 链接URL
            URLConnection conn = realUrl.openConnection();
            // 设置请求属性
            conn.setRequestProperty("Accept", "application/json");
            conn.setRequestProperty("Authorization", "Bearer " + bearer);//带的header参数
            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 PrintWriter(conn.getOutputStream());
            // 发送请求参数
            out.print(param);
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream()));
   ing line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
  }
      }
        }
        return result;
	}
  } 
post介绍

其中sendGetsendPostsendDelete三个接口都是正常的http接口。main测试如下:

   public static void main(String[] args) {
            String path="http://127.1.1.1:8080/queryConfigResource";//链接的接口路径
            System.out.println(path);
            String sss1 = GetPostUtil.sendPost(path, "orderId=1111201&workOrderId=1019"); //post参数用"="号表示,多个参数用"&"进行分割
            System.out.println(sss1);
  }
关于sendPostHeader

有时候会遇到一些其他的接口,比如会在post里边加入headers,对方接口信息如下

//接口详情
$response = $client->request('POST', 'http://127.0.0.1/resConfResponse', [
    'headers' => [
        'Accept' => 'application/json',
        'Authorization' => 'Bearer '.$token,
    ],
    'form_params' => [
    	'project_id' => '1',
    ],
]);

上边是对方给的接口信息,其中参数中带了headers和form_params两种,其中headers中指定了accept的格式,以及header带的参数Authorization,对应的Bearer 中的token,我直接写在了sendPostHeader接口内部(只是简单的加了一行),然后一样的带参数访问就好了。当然自己也可以根据遇到的对应的接口信息进行修改。

有一次遇到了raw格式的接口,以上的接口信息就不太适合了,然后自己单独写了一个方法类,有到的方法点过时了,但是还是记录一下吧

 /**
     * 获取接口数据
     */
    public static String resConfigResponse(String url, String json) {

        HttpClient httpClient = new DefaultHttpClient();//该方法会提示过时
//            HttpClient httpClient = new DefaultHttpClient();
        HttpPost post = new HttpPost(url);
        StringEntity postingString = null;// json传递
        String content = null;
        try {
            postingString = new StringEntity(json);

            post.setEntity(postingString);
            post.setHeader("Content-type", "application/json");
            org.apache.http.HttpResponse response = httpClient.execute(post);
            content = EntityUtils.toString(response.getEntity());
            System.out.println(content);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return content;


    }

注:1. HttpClient httpClient = new DefaultHttpClient();//该方法会提示过时
2. HttpClient client = HttpClientBuilder.create().build();//获取DefaultHttpClient请求

** 1 方法为我用的方法,会提示过时,可以用 2 方法代替

以上为我个人愚见,若有不对的地方,请给与指正,万分感谢!

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
GET、POST、PUT和DELETE是常见的HTTP请求方法。GET用于获取资源的信息,不会对服务器上的资源产生任何影响。POST用于向服务器提交数据,一般用于创建新的资源。PUT用于更新服务器上的资源,可以用于修改或替换已有的资源。DELETE用于删除服务器上的资源。 综上所述,HTTP请求方法的使用可以归纳为以下几种情况: - GET /url/xxx:用于获取指定资源的信息。 - POST /url:用于创建新的资源,提交数据到服务器。 - PUT /url/xxx:用于更新指定资源,修改或替换已有的资源。 - DELETE /url/xxx:用于删除指定资源。 更多关于这些HTTP请求方法的详细信息,您可以参考以下链接: - https://www.cnblogs.com/weibanggang/p/9454581.html - https://blog.csdn.net/qq_36183935/article/details/80570062 - https://blog.csdn.net/haif_city/article/details/78333213 - https://blog.csdn.net/justry_deng/article/details/80972817/<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* [Get、Put、PostDelete 含义与区别](https://blog.csdn.net/weixin_49770443/article/details/109805845)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] - *3* [总结get、put、postdelete的区别和用法](https://blog.csdn.net/weixin_56921066/article/details/118608143)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值