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;
    }

 

转载于:https://www.cnblogs.com/lostjoke/p/6067002.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值