java简易接口建立
服务端:
public void getOneStudent(String str1, String str2, String str3){ Student s = new Student();
s.setName("Tony");
s.setNum("123");
String message = JSONObject.toJSONString(s); //将类数据转成String字符串 String sb = null; try { sb = URLEncoder.encode(message, "UTF-8");//中文转码 } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } write(sb); } //把信息写到浏览器上 private void write(String message){ if(message == null){ message = "false"; /* set default false when the message is null */ } HttpServletResponse response = Result.getServletResponse(true); response.setCharacterEncoding("GBK"); PrintWriter writer; try { writer = response.getWriter(); writer.write(message); writer.close(); } catch (IOException e) { e.printStackTrace(); } }
访问端:
public static Student sendTheUrl(String str1, String str2, String str3){ Student s = null; String baseUrl = "http://localhost:8080/xxxx/getOneStudent?"; String urlStr = null; try { urlStr = baseUrl +"str1="+URLEncoder.encode(str1, "UTF-8")+"&str2="+str2+"&str3="+str4; } catch (UnsupportedEncodingException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } URL url = null; BufferedReader br = null; HttpURLConnection conn = null; StringBuffer sb = new StringBuffer(); try { url = new URL(urlStr); conn = (HttpURLConnection) url.openConnection(); br = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8")); String line = null; while( (line = br.readLine()) != null ){ sb.append(line); } if(sb !=null && !"".equals(sb)){ String a = URLDecoder.decode(sb.toString(), "UTF-8");//转码 s = JSONObject.parseObject(a, Student.class);//String转实体类 } } catch (Exception e) { LoggerUtil.errorLogger.error("请求搜索分类提示接口错误: " + e.toString()); }finally{ try { if(br != null){ br.close(); } if(conn != null){ conn.disconnect(); } } catch (IOException e) { e.printStackTrace(); } } return s; }