没有从改造/ Android /发送HTTP请求

时间:2017-04-14 13:50:19

标签: java android retrofit okhttp

我尝试使用Retrofit从我的Android项目向API发送数据。一切似乎没有错误,但没有http请求离开应用程序。我可以通过Wireshark筛选和API控制台日志来确认这一点。这是我的应用程序的这部分的示例伪代码:

// sample code

findViewById(R.id.submit_btn).setOnClickListener(this);

@Override
public void onClick(View v) {
    int i = v.getId();
    if (i == R.id.submit_btn){
        Intent intent = new Intent(CurrentActivity.this, HomeActivity.class);

        // myObj is class storing several values and it is defined in separate class
        MyObj obj = new MyObj(** some attributes here **);

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("http://api.address")
                .client(new OkHttpClient())
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        MyAPI api = retrofit.create(MyAPI.class);

        Call<Void> upload = api.newObj(obj);

        startActivity(intent);
        finish();
    }

不确定我错过了什么。有什么想法吗?

P.S。以下是应用程序为此部分使用的依赖项:

compile 'com.squareup.retrofit2:retrofit:2.1.0'
compile 'com.google.code.gson:gson:2.6.2'
compile 'com.squareup.retrofit2:converter-gson:2.1.0'
compile 'com.squareup.okhttp3:okhttp:3.0.1'

2 个答案:

答案 0 :(得分:2)

这只会准备请求,而不是发送请求。

Call<Void> upload = api.newObj(obj);

尝试制作upload.enqueue()

答案 1 :(得分:1)

您永远不会对该调用进行排队或执行,对服务器执行异步调用upload.enqueue(new CallBack here)执行同步立即使用upload.execute()