最近调试marathon的rest api接口,通过marathon的rest接口获得应用的配置信息。
由于marathon服务端配置了身份验证,在网页端打开的时候可以在页面输入用户名和密码进行访问,但是在程序里面进行访问的时候如何进行验证就无从下手了。
这几天在看Jersey 1.x 的官方文档,关于 Client API的介绍里面提到了Security with Http(s)URLConnection,参考实例如下:
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 RunHttpSpnego {
static final String kuser = "username"; // your account name
static final String kpass = "password"; // your password for the account
static class MyAuthenticator extends Authenticator {
public PasswordAuthentication getPasswordAuthentication() {
// I haven't checked getRequestingScheme() here, since for NTLM
// and Negotiate, the usrname and password are all the same.
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://192.168.3.13:8080/v2/apps");
InputStream ins = url.openConnection().getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(ins));
String str;
while((str = reader.readLine()) != null)
System.out.println(str);
}
}
以上代码通过用户名和密码验证,就可以访问marathon服务端并获取数据,参考地址:http://docs.oracle.com/javase/6/docs/technotes/guides/net/http-auth.html
既然Rest提供了客户端,我们也可以通过Client接口来进行身份验证,访问服务器,具体实现如下:
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 RestAuth {
public static void main(String[] args) {
Client client = Client.create();
client.addFilter(new HTTPBasicAuthFilter("username", "password"));
WebResource webResource = client
.resource("http://192.168.3.13:8080/v2/apps");
String res = webResource.accept(MediaType.APPLICATION_JSON).get(String.class);
System.out.println(res);
client.destroy();
}
}
这样,通过client接口也可以进行身份验证,访问marathon的服务端资源。
关于身份验证问题,在linux平台用curl访问服务端资源比较多,用curl也可以进行简单的用户名和密码验证。
#curl通过-u命令设置服务端的用户名和密码
#-u/--user <user[:password]> Set server user and password
curl -u username:password http://192.168.3.13:8080/v2/apps
版权声明:本文为tianpy5原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。