Spring java对象发送和接收

时间:2015-12-27 12:36:09

标签: java spring spring-mvc

我需要将Java对象从客户端发送到Spring控制器。我尝试了以下方法。但是没有工作。

我的bean类 - 我在客户端和服务中都有相同的包和类

public class DataObj implements Serializable {

    private String stringData;
    private byte[] byteData;
    public String getStringData() {
        return stringData;
    }
    public void setStringData(String stringData) {
        this.stringData = stringData;
    }
    public byte[] getByteData() {
        return byteData;
    }
    public void setByteData(byte[] byteData) {
        this.byteData = byteData;
    }
}

我的控制器

@RequestMapping(value = "/an/data", method = RequestMethod.POST)
public void subscribeUser(@RequestBody DataObj subscription){
    System.out.println("DD");
    bytes = subscription.getByteData();
}

我的客户 - Apache

HttpClient httpClient = HttpClientBuilder.create().build();
HttpPost httppost = new HttpPost("http://localhost:8080/contex/an/data");
httppost.setEntity(new SerializableEntity((Serializable) dataObj , false));
httpClient.execute(httppost);

我的客户 - URLConnection

  URL url = new URL("http://localhost:8080/contex/an/data");
  HttpURLConnection conn = (HttpURLConnection) url.openConnection();
  conn.setDoOutput(true);
  ObjectOutputStream  writer = new ObjectOutputStream (conn.getOutputStream());
  writer.writeObject(dataObj );
  writer.flush();
  conn.connect();
  writer.close();
  System.out.println(conn.getResponseCode());

执行都不起作用。控制器尝试重定向到访问被拒绝的页面。纠正我,如果我的理解是错误的,请原谅我,如果它是重复的。 JSON包装不会帮助我,因为java对象有字节数组。所以请注意。

更新 我收到了以下日志

org.apache.tomcat.util.http.Parameters processParameters INFO: Character decoding failed. Parameter...... [Showing my bean class package and the data in non readable format]

1 个答案:

答案 0 :(得分:0)

最后我找到了答案,总是Servlets就像King。我使用以下内容使其工作

@Autowired
private HttpServletRequest context;
@RequestMapping(value = "/an/data", method = RequestMethod.POST)
@ResponseBody
public String send() {
    System.out.println("EEE");
    try{
        ObjectInputStream obj =  new ObjectInputStream(context.getInputStream());
        DataObj v = (DataObj )obj.readObject();
        System.out.println(v.getStringData());
    }catch(Exception e){
        e.printStackTrace();
    }
return "CAME";
}