java调用接口之okhttp

JAVA调用restful接口

目前随着互联网微服务的兴起,需要通过接口进行服务的传输情况越来越多,原始的webservice相对较为臃肿,常见代表为aix2,xfire等等。新兴的则以restfull标准接口为代表的例如httpUrlConnection,okhttpclient,Unirest为代表。

首先先介绍一下httpurlconnection

本对象为JDK原生支持方法,不用引入任何第三方依赖包。具体代码如下:

    public static String sendGet(String url, String param) {
        String result = "";
        BufferedReader in = null;
        OutputStreamWriter out = null;
        try {//注意这里因为请求了spring发布的接口都是以html结尾的。
            URL realUrl = new URL(url+".html");
            // 打开和URL之间的连接
            URLConnection connection = realUrl.openConnection();
            // 设置通用的请求属性
            connection.setRequestProperty("accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
            connection.setRequestProperty("Connection", "keep-alive");
            connection.setRequestProperty("Accept-Encoding", "gzip, deflate, sdch");
            connection.setRequestProperty("Accept-Language", "zh-CN,zh;q=0.8");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("Accept-Charset", "utf-8");
            connection.setRequestProperty("user-agent","Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.104 Safari/537.36 Core/1.53.4620.400 QQBrowser/9.7.13014.400");
            connection.setDoOutput(true);
            connection.setDoInput(true);
            out = new OutputStreamWriter(connection.getOutputStream(),"utf-8"); 
            // 发送请求参数
            out.write("param="+param);
            // flush输出流的缓冲
            out.flush();
            in = new BufferedReader(new InputStreamReader(connection.getInputStream(),"utf-8"));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("发送GET请求出现异常!" + e);
            e.printStackTrace();
        }
        // 使用finally块来关闭输入流
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return result;
    }
    

接下来介绍一下okhhtp

使用okhttp首先要引入依赖包,pom资源库增加

		<!-- http请求接口 -->
		<dependency>
		    <groupId>com.squareup.okhttp3</groupId>
		    <artifactId>okhttp</artifactId>
		    <version>4.6.0</version>
		</dependency>

接下来我们看JAVA代码:

	public static String send(String url, String param) {
		OkHttpClient client = new OkHttpClient().newBuilder().build();
		MediaType mediaType = MediaType.parse("text/plain");
		RequestBody body = RequestBody.create(mediaType, "");
		Request request = new Request.Builder().url(WEB_URL + url + "?" + param).method("POST", body).build();
		try {
			Response response = client.newCall(request).execute();
			if (response.isSuccessful()) {// 请求成功
				return response.body().string();
			} else {
				return "";
			}
		}catch (IOException e) {//接口请求异常-直接返回空
			e.printStackTrace();
			return "";
		}


	}

对比一下第一个更像是通过浏览器抓包给的数据接口的发那个是,尤其对conn.set各种属性,第二个封装的较为简洁,第二个也是Postman推荐的java代码的使用方式。

上面代码占到ide就能执行,不想动手复制的,也可以直接到这里去下载:
https://download.csdn.net/download/Himly_Zhang/12440433

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值