且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

改造:发送POST请求到服务器的android

更新时间:2023-02-26 13:35:50

在等待我想回答我的问题的***的回应之后。这是我解决我的问题。

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

我改变RetrofitService的RestAdapter的转换器和创建了自己的转换器。下面是我StringConverter

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();
    }
}

然后我设置的转换器在应用程序类的RestAdapter。

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);

现在,每当我用的改造,我得到的字符串的响应。然后,我转换的字符串JSONObject的。

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<String>() {

    @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);
    }
});

因此​​,我得到的结果JSON形式。然后我分析这个JSON的要求。

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