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);
    }
}


猜你喜欢

转载自blog.csdn.net/liaryank/article/details/80857823