Retrofit: Sending POST request to server in android

后端 未结 2 416
误落风尘
误落风尘 2021-01-12 23:59

I am using Retrofit to call APIs. I am sending a post request to API but in the callback I am getting empty JSON like this {}.

Below is the code for RetrofitService<

2条回答
  •  抹茶落季
    2021-01-13 00:33

    After waiting for the best response I thought of answering my own question. This is how I resolved my problem.

    I changed the converter of RestAdapter of RetrofitService and created my own Converter. Below is my StringConverter

    static class StringConverter implements Converter {
    
        @Override
        public Object fromBody(TypedInput typedInput, Type type) throws ConversionException {
            String text = null;
            try {
                text = fromStream(typedInput.in());
            } catch (IOException ignored) {/*NOP*/ }
    
            return text;
        }
    
        @Override
        public TypedOutput toBody(Object o) {
            return null;
        }
    
        public static String fromStream(InputStream in) throws IOException {
            BufferedReader reader = new BufferedReader(new InputStreamReader(in));
            StringBuilder out = new StringBuilder();
            String newLine = System.getProperty("line.separator");
            String line;
            while ((line = reader.readLine()) != null) {
                out.append(line);
                out.append(newLine);
            }
            return out.toString();
        }
    }
    

    Then I set this converter to the RestAdapter in the Application class.

    RestAdapter restAdapter = new RestAdapter.Builder()
            .setEndpoint(BASE_URL)
            .setConverter(new StringConverter())
            .build();
        mRetrofitService = restAdapter.create(RetrofitService.class);
    

    Now whenever I use Retrofit, I get the response in String. Then I converted that String JSONObject.

    RetrofitService mRetrofitService = app.getRetrofitService();
    mRetrofitService.getUser(user, new Callback() {
    
        @Override
        public void success(String result, Response arg1) {
            System.out.println("success, result: " + result);
            JSONObject jsonObject = new JSONObject(result);
        }
    
        @Override
        public void failure(RetrofitError error) {
            System.out.println("failure, error: " + error);
        }
    });
    

    Hence, I got the result in JSON form. Then I parsed this JSON as required.

提交回复
热议问题