我需要将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 processParametersINFO: Character decoding failed. Parameter...... [Showing my bean class package and the data in non readable format]

最佳答案

终于我找到了答案,总是Servlet就像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";
}

08-17 02:41