2017-04-14 42 views
0

我想从我的Android项目使用改进将数据发送到API。一切似乎没有错误的工作,但没有http请求离开应用程序。我可以用Wireshark筛选和API控制台日志来证实这一点。这里是我的应用程序的这一部分的示例伪代码:没有HTTP请求是从改造发送/ Android/

// 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' 

回答

1

这只准备请求,不发送它。

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

尝试使upload.enqueue()

+0

谢谢,这解决了这个问题。改造官方的例子不够详细。当你提到排队时,我找到了原始文档。如果需要,以下是其他人的链接:https://square.github.io/retrofit/2.x/retrofit/retrofit2/Call.html#enqueue-retrofit2.Callback- – nikitz

+0

这是实际的文档。 https://github.com/square/retrofit/wiki/Retrofit-Tutorials –

1

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