服务器端servlet怎么将json的值返回客户端,请详细讲解下
客户端代码:
public class SkimFile {
public String Skim(){
String rvalue="";
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpPost httppost = new HttpPost("http://localhost:8080/httpclientweb/skim.action");
List<BasicNameValuePair> formparams = new ArrayList<BasicNameValuePair>();
formparams=null;
UrlEncodedFormEntity uefEntity;
try {
uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8");//urlEncoding
httppost.setEntity(uefEntity);
System.out.println("executing request " + httppost.getURI()); //获取httppst访问地址
CloseableHttpResponse response = httpclient.execute(httppost);
try {
HttpEntity entity = response.getEntity(); //获得响应实体
if (entity != null) {
rvalue=EntityUtils.toString(entity, "UTF-8");
}
} finally {
response.close();
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
// 关闭连接,释放资源
try {
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return rvalue;
}
}
客户端:
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
Userdao userdao=new Userdao();
List list=userdao.queryUser();
String temp=new String();
for(int i=0;i<list.size();i++){
User user=(User)list.get(i);
System.out.println(user.getId());
temp +=user.getId()+" ";
temp +=user.getPassword()+" ";
temp +=user.getName()+"|";
}
temp=temp.substring(0,temp.length()-1);
System.out.println("Start"+temp);
out.flush();
out.close();
}