org.springframework.web.client.HttpClientErrorException:415不支持的媒体类型[已编辑]

时间:2017-05-31 06:40:57

标签: android spring post resttemplate

在使用REST TEMPLATE的POST方法的Android Web服务中,我正在尝试将对象发送到包含少量参数和2个对象的服务器。这2个对象包含很少的参数和3个不同对象的列表,这3个对象列表中的每一个都包含很少的参数和1个仅包含字节数组的对象列表。就像下面的图片一样:

图1 [主要对象(我要发送的那个)]:

Main Object(The one I am trying to send)

图2 [包含3个对象列表的主对象内的对象]:

Object inside the Main Object comprising 3 Lists of Objects

图3 [作为列表的对象,其中包含1个另一个对象列表,同样用于其他2个(住宿及其他)]:

An Object as List comprising 1 List of Another Object inside it, likewise for the other 2(Accommodation & Others)

图4 [仅包含一个byre数组参数的子对象内的对象列表]:

List of Object inside the sub-Object containing a byre array parameter alone

我的webservice POST方法代码:

public static final String capUrl = "http://192.168.1.7:8084/CAPWS";

public Expenses setExpensesByBatch(Expenses expenses) {

    try {

        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);

        RestTemplate restTemplate = new RestTemplate();
        restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
        restTemplate.getMessageConverters().add(new StringHttpMessageConverter());
        restTemplate.setRequestFactory(new HttpComponentsClientHttpRequestFactory());

        List<HttpMessageConverter<?>> list = new ArrayList<HttpMessageConverter<?>>();
        list.add(new MappingJacksonHttpMessageConverter());
        restTemplate.setMessageConverters(list);


        String b = restTemplate.postForObject(capUrl + "/UX/", expenses, String.class);

        Log.e("String ===============b", b + "     ++++");

    } catch (Exception e) {
        e.printStackTrace();
        Log.e("expObjPost_WsCli_EX", e.toString());
    }
    return expenses;
}

无论我做什么,都会返回org.springframework.web.client.HttpClientErrorException: 415 Unsupported Media Type

我的下方LOGCAT

LOGCAT

我的服务器端代码:

@RequestMapping(value = CapRestURIConstants.UPDATEEXPENSES, method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
public @ResponseBody
String updateExpenses(@RequestBody Expenses expenses) {
    String response = "true";

    System.out.println("incoming--------" + "UPDATEEXPENSES");
    try {
        if (expenses != null) {
            //System.out.println("expenses--------" + expenses);

            int catType = expenses.getCategoryType();
            String categoryType = String.valueOf(catType);

            String categoryId = expenses.getCategoryId();
            String batchId = expenses.getBatchId();

            System.out.println("categoryType--------" + categoryType);
            System.out.println("categoryId--------" + categoryId);
            System.out.println("batchId--------" + batchId);

            Batch batch = getBatchById(batchId);
            if (batch != null) {

                expenseDataNew(batch, expenses);
                expenseImagesNew(batch, expenses);
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
        response = "faslse";
    }
    return response;
}

public void expenseDataNew(Batch batch, Expenses expenses) {

    Session session = null;
    Transaction transaction = null;
    Gson gson = new Gson();

    try {

        LinkedTreeMap masterMap = (LinkedTreeMap) gson.fromJson(batch.getMasterJson(), Object.class);
        LinkedTreeMap expenseObject = (LinkedTreeMap) masterMap.get("2007");

        masterMap.replace(expenseObject, expenses);
        String masterJson = gson.toJson(masterMap);
        batch.setMasterJson(masterJson);

        session = HibernateUtil.getSessionFactory().openSession();
        transaction = session.beginTransaction();
        session.saveOrUpdate(batch);

        transaction.commit();

    } catch (Exception e) {
        if (transaction != null) {
            transaction.rollback();
        }
        e.printStackTrace();
    } finally {
        if (session != null) {
            session.close();
        }
    }
}

public void expenseImagesNew(Batch batch, Expenses expenses) {

    Session session = null;
    Transaction transaction = null;
    Gson gson = new Gson();

    try {

        // DIVERTING TO IMAGE DB
        session = ImageHibernateUtil.getSessionFactory().openSession();
        transaction = session.beginTransaction();

        if (expenses != null) {


            int catType = expenses.getCategoryType();
            String categoryType = String.valueOf(catType);
            System.out.println("categoryType--------" + categoryType);

            String categoryId = expenses.getCategoryId();
            System.out.println("categoryId--------" + categoryId);

            String travelExpenseImgId = "f257f225-41da-11e7-be05-001d92ba9634";
            String accommodationExpenseImgId = "204b4baf-41db-11e7-be05-001d92ba9634";
            String otherExpenseImgId = "45d31872-41db-11e7-be05-001d92ba9634";

            AssessorExpense assessorExpense = expenses.getAssessorExpense();
            TCExpense tCExpense = expenses.getTcExpense();

            Boolean isTravel, isAccomadation, isOthers;

            List<Travel> travelList;
            List<Accomadation> accommodationList;
            List<Others> othersList;

            ArrayList proof;
            Expense expense;
            ExpenseImage expenseImage;

            // categoryType: 1 = Assessor
            // categoryType: 4 = TC
            if (categoryType.equals("1")) {

                if (assessorExpense != null) {

                    isTravel = assessorExpense.isTravel();
                    if (isTravel) {

                        travelList = (ArrayList) assessorExpense.getTravel();
                        System.out.println("travelList.size()==" + travelList.size());

                        expense = getExpense(travelExpenseImgId);
                        System.out.println("expense==travel==1==:" + expense);
                        String expenseStr = String.valueOf(expense);
                        System.out.println("expenseStr==travel==1==:" + expenseStr);


                        for (Travel travel : travelList) {

                            List<ExpenseImageObject> expenseImageObjects = (ArrayList) travel.getExpenseImageObjects();
                            System.out.println("travel==expenseImageObjects.size()== :" + expenseImageObjects.size());

                            for (ExpenseImageObject image : expenseImageObjects) {

                                System.out.println("expense===travel==for==:" + expense);

                                expenseImage = new ExpenseImage();

                                expenseImage.setBatchId(batch.getBatchId());
                                expenseImage.setCategoryId(expenses.getCategoryId());
                                expenseImage.setExpimgId(expenseStr);
                                expenseImage.setImage(image.getImage());
                                expenseImage.setStatus(1);   // dummy status 1 - Travel, 2 - Accommodation, 3 - Other

                                session.saveOrUpdate(expenseImage);                                    
                            }
                        }
                    }
                }
            }
        }
        transaction.commit();

    } catch (Exception e) {
        if (transaction != null) {
            transaction.rollback();
        }
        e.printStackTrace();
    } finally {
        if (session != null) {
            session.close();
        }
    }
}

我实际上是在尝试将包含数据列表的对象以及每个列表中的照片列表发送到服务器。 浏览了几个网站以及与Stack Overflow上的错误相关的几乎所有主题,已经在这个问题上待了一个多星期。希望我能找到一些帮助。

3 个答案:

答案 0 :(得分:0)

将通话更改为此类

HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
headers.add("Accept","application/json;charset=utf-8");

RestTemplate restTemplate = new RestTemplate();
...
HttpEntity request = new HttpEntity(req, headers);
responseEntity = restTemplate.exchange(url, HttpMethod.POST, request,
    String.class);

指定内容类型

更新

req实际上是您发送给服务器的正文。它可能是例如。

MultiValueMap<String, Object> req ...

你实际上发送了请求正文和标题。

答案 1 :(得分:0)

尝试使用“HttpHeaders”将内容类型标头明确设置为端点所期望的内容。 然后使用标题和身体类的“HttpEntity”。 示例:

sudo chmod o+x /usr/local/sbt/sbt /usr/local/sbt/sbt-launch.jar

答案 2 :(得分:0)

经过大量的研究和专家建议,我终于找到了解决问题的方法。问题不在于代码。它实际上很完美。问题在于我用来获取和使用的对象。组。我正在使用 NetBeans 进行服务器端编码。我做的是,我在 Android studio 中创建了必要的对象,复制了参数 getters&amp; setters 并将它们粘贴到 NetBeans ,Object类上。问题在于我一直在使用的布尔值。在 Android Studio 上创建的布尔在某些情况下不支持 NetBeans ,从而无法访问服务器。在获得专家建议后,我在 NetBeans 上创建了对象,复制了参数 getters&amp; setters 并将它们粘贴在 Android Studio 对象类上。然后它运作良好。花了我两个多星期才解决这个问题。希望这会有所帮助。