您的位置:首页 > 编程语言 > Java开发

JAVA调用restful接口,通过Cookie跳过权限验证

2018-03-02 13:42 1101 查看
这两天项目上用到restful,自己写了restful接口,然后在java中调用,项目中配有登录验证的过滤器。
在网上搜了很多方式都是无状态的调用方式。最后综合了网上很多资料总结出一下两种方式:
1.通过HttpClient方式:

    HttpClient httpclient = new DefaultHttpClient();
    String url = "http://10.0.102.192:8080/avidm/rest/docStandardEx/A1";
    try {
        HttpPost httppost = new HttpPost(url);
httppost.addHeader("Content-type","text/xml; charset=GB2312");
httppost.setHeader("XASPSESSION", "123");
httppost.addHeader("Cookie", "sessionId");
HttpResponse post = httpclient.execute(httppost);
if (post.getStatusLine().getStatusCode() == 200) {
String conResult = EntityUtils.toString(post.getEntity());
JSONObject sobj = new JSONObject();
sobj = JSONObject.fromObject(conResult);
System.out.println(sobj);
}
    } catch (Exception e) {
 e.printStackTrace();
    } finally {
//关闭连接
    }
2.通过HttpURLConnection方式:
URL url = new URL("http://localhost:8080/avidm/rest/docStandardEx/A1");
//打开restful链接 
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
// 提交模式  
conn.setRequestMethod("GET");//POST GET PUT DELETE  
//可以解决部分400报错
conn.setRequestProperty("Content-Type", "text/xml; charset=GB2312");
HttpSession se = request.getSession();
String sessionId = se.getId();
//获取当前登录的sessionID放在cookie中,解决conn中无法获取当前session的问题
conn.setRequestProperty("Cookie", "JSESSIONID="+sessionId);
conn.setDoInput(true);
InputStream inStream = null;
System.out.println(conn.getResponseCode());
if (conn.getResponseCode() >= 200) {
inStream = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(inStream));
        String line = reader.readLine();
}
conn.disconnect();
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  JAVA RESTFUL