2017-05-04 6 views
1

私のウェブサイトからデータを正常に取得しましたが、情報を送信したり、送信した内容を確認することはできません。 私はここでたくさんのスレッドを読んでいますが、誰も私を助けることができませんでした。ここにJSONデータ送信機能があります。Androidスタジオで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

UIスレッドで実行するのに時間がかかるOnCreate()にメソッドを配置する必要はありません。 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); 
関連する問題