2017-05-04 307 views
1

我已經成功從我的網站獲取數據,但無法發送信息並查看我發送的內容。 我在這裏讀了很多線索,他們都無法幫助我。這是我的JSON數據發送器函數。在Android Studio中發送和接收返回的JSON數據

protected void sendJson(final String email, final String pwd) { 
    Thread t = new Thread() { 

     public void run() { 
      Looper.prepare(); //For Preparing Message Pool for the child Thread 
      HttpClient client = new DefaultHttpClient(); 
      // HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000); //Timeout Limit 
      HttpResponse response; 
      JSONObject json = new JSONObject(); 

      try { 
       HttpPost post = new HttpPost("https://www.google.com.br/mobile/test/"); 

       json.put("name", email); 
       json.put("senha", pwd); 

       Log.d("TAG InfoDesejada", json.toString()); 
       StringEntity se = new StringEntity(json.toString()); 
       Log.d("TAG StringEnviada", se.toString()); 
       se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json")); 
       post.setEntity(se); 
       response = client.execute(post); 


       /*Checking response */ 
       if (response != null) { 
        InputStream in = response.getEntity().getContent(); //Get the data in the entity 
        Log.d("TAG TextoEnviado4", response.toString()); 
       } 

      } catch (Exception e) { 
       e.printStackTrace(); 
       Log.d("Error", "Cannot Estabilish Connection"); 
      } 

      Looper.loop(); //Loop in the message queue 
     } 
    }; 

    t.start(); 
} 

然後我打電話在MainActivity:sendJson("[email protected]", "password");

我不知道如果我正確地發送數據,但如果我不知道如何檢索,或者這方面的工作數據無論如何。 真的需要幫助。謝謝。

+0

這sendJson函數被調用的onCreate()? – redAllocator

+0

是的。它叫onCreate。 –

回答

0

您不必在OnCreate()中放置需要一些時間在UI線程上執行的方法。 我想推薦使用AsyncTask。

AsyncTask支持正確和方便地使用UI線程。 該類允許您執行背景操作並在UI線程上發佈結果,而無需操縱線程和/或處理程序。

這個例子:

private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> { 
     protected Long doInBackground(URL... urls) { 
      int count = urls.length; 
      long totalSize = 0; 
      for (int i = 0; i < count; i++) { 
       totalSize += Downloader.downloadFile(urls[i]); 
       publishProgress((int) ((i/(float) count) * 100)); 
       // Escape early if cancel() is called 
       if (isCancelled()) break; 
      } 
      return totalSize; 
     } 

     protected void onProgressUpdate(Integer... progress) { 
      setProgressPercent(progress[0]); 
     } 

     protected void onPostExecute(Long result) { 
      showDialog("Downloaded " + result + " bytes"); 


    } 
} 

一旦創建了任務執行得很乾脆:

new DownloadFilesTask().execute(url1, url2, url3);