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

这两天项目上用到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();


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值