JAVA调restful接口实例

java 调resrful接口实则不难,本文介绍两种调用方式。

   ①使用client调用②使用流方式调用。

一  使用client调用,实现以下两点即可

1 .下载所需jar包,下载地址为本文所选版本为1.19.1。

https://jersey.github.io/download.html

2. 注意返回格式是json还是xml或其它。

 

     废话不多说,请看代码:

import javax.ws.rs.core.MediaType;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.WebResource;

import com.sun.jersey.api.client.filter.HTTPBasicAuthFilter;

 

 

public class testRestfulClient {
    public static void main(String[] args) {

 

 

        Client client = Client.create();

 

        client.addFilter(new HTTPBasicAuthFilter("用户名", "密码"));
        WebResource webResource = client
                .resource("http://-------------URL-------");
        //String result = (String)call.invoke(new Object[]{xml});
        String res = webResource.accept(MediaType.APPLICATION_ATOM_XML).get(String.class);
        System.out.println(res);
        client.destroy();
    }
}

 

二  使用流方式调用,只需引入jdk即可

     代码实例:

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.Authenticator;
import java.net.PasswordAuthentication;
import java.net.URL;

public class testRestful {

    static final String kuser = "用户名"; // your account name

    static final String kpass = "密码"; // your password for the account

 

    static class MyAuthenticator extends Authenticator {
        public PasswordAuthentication getPasswordAuthentication() {
            System.err.println("Feeding username and password for " + getRequestingScheme());
            return (new PasswordAuthentication(kuser, kpass.toCharArray()));
        }
    }
    public static void main(String[] args) throws Exception {
        Authenticator.setDefault(new MyAuthenticator());

 

        URL url = new URL("http://-----URL----");

 

        InputStream ins = url.openConnection().getInputStream();
        BufferedReader reader = new BufferedReader(new InputStreamReader(ins));
        String str;
        while((str = reader.readLine()) != null)
            System.out.println("返回结果:"+str);
    }
}

 

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值