2015-11-08 122 views
1

我目前在執行我的發佈請求時出錯。我試圖做別人推薦的其他計算器鏈接,但它不適合我。以下是我的代碼:Android OKHTTP發佈請求

public void postGames(View v) { 
    //Sets the data input by user into variables 
    TextView gameName = (TextView) findViewById(R.id.gameName); 
    TextView companyName = (TextView) findViewById(R.id.companyName); 
    TextView consoleName = (TextView) findViewById(R.id.consoleName); 
    final TextView resultMessage = (TextView) findViewById(R.id.postResult); 

    //Set up the url 
    String gamesUrl = "sampleurl..."; 

    //Creates the HTTP client and puts the url info in it 
    OkHttpClient client = new OkHttpClient(); 
    RequestBody formBody = new FormEncodingBuilder() 
      .add("name", "hello") 
      .add("company", "world") 
      .add("console", "Blagh") 
      .build(); 
    Request request = new Request.Builder() 
      .url(gamesUrl) 
      .post(formBody) 
      .build(); 

    //First checks if the network is available 
    if (isNetworkAvailable()) { 
     //Executes the post request 
     try { 
      Response response = client.newCall(request).execute(); 
      if(response.isSuccessful()){ 
       resultMessage.setText("Post successful..."); 
      } 
     } catch (IOException e) { 
      e.printStackTrace(); 
      resultMessage.setText("Error in executing post request..."); 
     } 

    } else { 
     Toast.makeText(this, getString(R.string.network_unavailable_message), 
       Toast.LENGTH_LONG).show(); 
    } 
} 

它給出了「Response response = client.newCall(request).execute();」的錯誤。線。有什麼我在這裏做錯了嗎?

+0

您應該發佈堆棧跟蹤 - 或者至少說明錯誤是什麼... – Jim

+0

您無法在同一個線程上同時執行網絡和設置文本。你的錯誤可能是主線程錯誤的一個微不足道的網絡。\ – njzk2

回答

1

嘗試實現這樣的迴應:

final Call call = okHttpClient.newCall(request); 
     call.enqueue(new Callback() { 
         @Override 
         public void onFailure(Request request, final I 
           } 
          }); 
         } 
         @Override 
         public void onResponse(final Response response) 
           throws IOException { 
          } 
         } 
        } 
0

由於您使用OkHttp的同步方式,所以在Android中,你必須使用它裏面的AsyncTask。您的應用程序可能已經獲得了NetworkOnMainThreadException。

如果你不想要AsyncTask,你應該以異步方式實現OkHttp。

恕我直言,你可以在

https://github.com/square/okhttp/wiki/Recipes

找到更多的信息,並在以下問題有一個很好的答案可以用SO:

Using OKHttp, what is the difference between synchronous request in AsyncTask and OKhttp Asynchronous request?

希望這有助於!