spring mvc中设置返回的http status自定义编码

spring mvc  action  基类

package com.peidw.actions;
import org.springframework.web.bind.annotation.ModelAttribute;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;


/**
 *
 * ModelAttribute 表示先执行吗
 * Created by peidw on 2015/7/15.
 */
public class BaseController {
    protected HttpServletRequest request;
    protected HttpServletResponse response;
    protected HttpSession session;

    @ModelAttribute
    public void setReqAndRes(HttpServletRequest request, HttpServletResponse response){
        this.request = request;
        this.response = response;
        this.session = request.getSession();
    }
}



restful action类

package com.peidw.actions;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by peidw on 2015/12/4.
 */
@RestController
public class RestDemo extends BaseController{

    @RequestMapping("restDemo.do")
    public String restDemo(){
        response.setHeader("Content-Type", "application/json");
        //content-type为application/x-json;charset=UTF-8
        response.setStatus(560);
        return "{\"code\":\"560\",\"detail\":\"出现异常\"}";
    }
}

启动服务,访问地址是:

http://127.0.0.1:8080/restDemo.do


客户端测试代码(因为用springboot对资源加了访问验证):

package com.peidw.actions;

import org.apache.log4j.Logger;
import org.junit.Test;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.*;

/**
 * Created by peidw on 2015/12/4.
 */
public class RestDemoTest {
    private static Logger logger= Logger.getLogger(RestDemoTest.class);
    @Test
    public void test(){

        HttpURLConnection connet = null;
        try {
            MyAuthenticator myau=new MyAuthenticator("admin","test");
            Authenticator.setDefault(myau);
            URL url = new URL("http://127.0.0.1:8080/restDemo.do");
            connet = (HttpURLConnection) url.openConnection();
            connet.setConnectTimeout(120000);

            BufferedReader brd = null;
            try {
                brd = new BufferedReader(new InputStreamReader(connet.getInputStream()));
            } catch (Exception e) {
                brd = new BufferedReader(new InputStreamReader(connet.getErrorStream()));
            }
            String result = brd.readLine();


            logger.info("result="+result);

            String rsp_code=String.valueOf(connet.getResponseCode());
            logger.info("rsp_code="+rsp_code);

        } catch (Exception e) {
            e.printStackTrace();
            logger.info("EcaopServ调用失败:"+e.getMessage());

        } finally {
            if (null != connet) {
                connet.disconnect();
            }
        }
    }

}
class MyAuthenticator extends Authenticator {

    private String name;

    private String passwd;

    private boolean authentError; //检查是否认证失败

    public MyAuthenticator(String name, String passwd) {
        this.name = name;
        this.passwd = passwd;
    }

    protected PasswordAuthentication getPasswordAuthentication() {
        String promptString = getRequestingPrompt();
        String hostname = getRequestingHost();
        InetAddress ipaddr = getRequestingSite();
        if (promptString != null && hostname != null && ipaddr != null) {
            authentError = true;
        } else {
            authentError = false;
        }

        String username = name;
        String password = passwd;
        return new PasswordAuthentication(username, password.toCharArray());
    }

    public void setAuthentError(boolean authentError) {
        this.authentError = authentError;
    }

    public boolean isAuthentError() {
        return authentError;
    }
}

测试结果:


2015-12-04 18:23:08.512  INFO   --- [           main] com.peidw.actions.RestDemoTest           : result={"code":"560","detail":"出现异常"}
2015-12-04 18:23:08.520  INFO   --- [           main] com.peidw.actions.RestDemoTest           : rsp_code=560



评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值