在成功方法上改进空响应

时间:2017-12-05 19:22:14

标签: javascript java android node.js retrofit2

我在YouTube for Retrofit中关注此tutorial以便在帖子请求中发送对象,但在模拟器上遇到错误,其响应为 onResponse 方法。

问题: Null Response on Response

主要活动:

public class MainActivity extends AppCompatActivity {


private EditText mName, mEmail, mAge, mTopics;
private Button mButton;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    mName = findViewById(R.id.editText);
    mEmail = findViewById(R.id.editText2);
    mAge = findViewById(R.id.editText3);
    mTopics = findViewById(R.id.editText4);
    mButton = findViewById(R.id.button);

    mButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            User user = new User(
                    mName.getText().toString(),
                    mEmail.getText().toString(),
                    Integer.parseInt(mAge.getText().toString()),
                    mTopics.getText().toString().split(",")
            );

            //Added proof its not a NPE!!!!!!!!!!!!!!!!!!!!!!!!!!!!! 
            Log.d("Main", mName.getText().toString() +
                            mName.getText().toString()+ Integer.parseInt(mAge.getText().toString()) +
                            Integer.parseInt(mAge.getText().toString()) +mTopics.getText().toString().split(","));

            sendNetworkRequest(user);
        }
    });

}

private void sendNetworkRequest(User user) {
    Retrofit.Builder builder = new Retrofit.Builder()
            .baseUrl("http://10.0.2.2:3000/api/users/")
            .addConverterFactory(GsonConverterFactory.create());

    Retrofit retrofit = builder.build();
    UserClient client = retrofit.create(UserClient.class);
    Call<User> call = client.createAccount(user);
    call.enqueue(new Callback<User>() {
        @Override
        public void onResponse(Call<User> call, Response<User> response) {
            Toast.makeText(MainActivity.this, "Success UserID = "+ response.body(), Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onFailure(Call<User> call, Throwable t) {
            Toast.makeText(MainActivity.this, "Failure", Toast.LENGTH_SHORT).show();
        }
    });

}

}

NOT NPE的证明:

NOT NPE

UserClient:

public interface UserClient {

    @POST("api/users")
    Call<User> createAccount(@Body User user);
}

用户:

public class User {

private Integer id;
private int age;
private String name, email;
private String [] topics;

public Integer getId() {
    return id;
}

public User(String name, String email, int age,  String[] topics) {
    this.age = age;
    this.name = name;
    this.email = email;
    this.topics = topics;
}

Node.js的

App.js

const express = require('express');
const bodyParser = require('body-parser');
const routes = require('./routes/api');
const mongoose = require('mongoose');

const app = express();

mongoose.connect('mongodb://localhost/user1',  { useMongoClient: true });
mongoose.Promise = global.Promise;


app.use(bodyParser.json());
app.use('/api', routes);

app.listen(process.env.port || 3000, function(){
    console.log('Using PORT 3000');
});

Api.js:

const express = require('express');
const router = express.Router();
const User = require('../models/user');

router.get('/users', function(req, res, next){
    res.send({type: "GET"});
});

router.post('/users', function(req, res, err){
    User.create(req.body).then(function(user){
        res.send(user);
    });
});

module.exports = router;

user.js的

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const UserSchema = new Schema({
    name: {
        type: String
    },
    email: {
        type: String
    },
    age: {
        type: Number
    },
    topics: {
        type: String
    }
});

const User = mongoose.model('user', UserSchema);

module.exports = User;

我尝试了什么:

  • 我尝试使用&#39; ipconfig&#39;更改 BASE_URL 我机器的本地IP地址在我的终端上。 =&#39; http://192.168.X.X:3000/api/users/&#39;
  • UserClient = @Headers中使用标题和FormURLEncoded (&#34; Content-Type:application / json&#34;)| @FormUrlEncoded。
  • 使用邮递员检查成功发生的回复。
  • 检查Robomongo进行验证/

邮差:

获取请求 Get Request

发布请求 Post Request

Robomongo Robomongo

2 个答案:

答案 0 :(得分:2)

BaseURL应为:baseUrl("http://10.0.2.2:3000/"),因为您的UserClient界面有以下路径:

@POST("api/users")
Call<User> createAccount(@Body User user);

<强>更新

您的主题字段应为String而不是String[]

改变这个:

private String [] topics;

对此:

private String topics;

答案 1 :(得分:0)

也许你的请求不好?

尝试在onResponse()中添加null检查并访问原始响应,如此response.errorBody.string()