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