Java对象会通过HttpURLConnection调用

时间:2019-01-16 13:21:03

标签: java json spring-boot http-post httpurlconnection

我正在尝试使用HttpURLConnction发布到一些其他服务端点。 问题是,我尝试使用post方法传递的对象能够检索到接收者端点,但无法将其强制转换回原始类型。该对象已自动转换为linkedhasmap。我该如何取回物体。预先感谢。

发件人应用程序示例代码:

UsersInformation userInfo = new UsersInformation();

        InputUserObject inputUserObject = new InputUserObject();
        inputUserObject.setUserObject("usersInformation", userInfo);


Gson gson = new GsonBuilder().disableHtmlEscaping().setPrettyPrinting()
                .create();

        Type type = new TypeToken<InputUserObject>() {
        }.getType();
        String jsonInString = gson.toJson(inputUserObject, type);


String requestURL = "receiver endpoint";
        URL url;
        try {
            url = new URL( requestURL );

            HttpURLConnection conn;
            conn = (HttpURLConnection) url.openConnection();

            conn.setDoOutput( true );
            conn.setInstanceFollowRedirects( false );
            conn.setRequestMethod( "POST" );
            conn.setRequestProperty( "Content-Type", "application/json");
            conn.setRequestProperty( "charset", "utf-8");
            conn.setUseCaches( false );

            try( DataOutputStream wr = new DataOutputStream( conn.getOutputStream())) {
              wr.writeChars(jsonInString);


              BufferedReader br = null;
              if (200 <= conn.getResponseCode() && conn.getResponseCode() <= 299) {
                    br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
              }else{
                    br = new BufferedReader(new InputStreamReader(conn.getErrorStream()));
              }
              String outputData = org.apache.commons.io.IOUtils.toString(br);

            }


        }catch (MalformedURLException e) {

            e.printStackTrace();
        }

        catch (IOException e1) {

            e1.printStackTrace();
        }

接收器应用程序示例代码:

@RequestMapping(value = <receiver endpoint>, method = RequestMethod.POST, produces = "application/json", consumes = "application/json")
    public String testForDataTransferFromMVC(
            @RequestBody InputUserObject inputJSONObj) {


        LOGGER.debug("inputJSONObj -"+inputJSONObj); // here i can receive the object and it is in linkedhasmap type

        UsersInformation usersInformation = inputJSONHashmap.get("usersInformation"); // this throws type cast exception that it cannot convert from linkedhashmap to UsersInformation
        Map<String, Object> usersInformation = (Map<String, Object>) inputJSONHashmap.get("usersInformation"); // This line worked perfectly

0 个答案:

没有答案