簡體   English   中英

無法獲得適用於Android的GET請求

[英]Cannot get GET request working for Android

我試圖向我的本地NodeJS服務器發出一個簡單的GET請求來獲取一些JSON對象。 我更改了請求,因此它發生在AsyncTask而不是UI線程中。 但我仍然無法讓它發揮作用。 這段代碼看起來是否正確? 對不起,Java還不是很好。

    package com.dd.relay;

import com.dd.relay.HttpRequest;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import android.app.ListActivity;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends ListActivity {
    public final static String EXTRA_MESSAGE = "com.dd.relay.MESSAGE";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);

             // We'll define a custom screen layout here (the one shown above), but
             // typically, you could just use the standard ListActivity layout.
             setContentView(R.layout.activity_main);


          // Make a GET request for data
             String url = "http://localhost.com/contacts";
             String res = null;
             try {
                HttpRequest request = new HttpRequest();
                request.execute(new URL(url));

                Log.v(EXTRA_MESSAGE, res);
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

             TextView textView = (TextView) findViewById(R.id.textv);
             Context context = this.getApplicationContext();
             Toast mytoast = Toast.makeText(context,  res, Toast.LENGTH_LONG);
             mytoast.show();
             textView.setText(res);
            // Create list for contacts
            /* List<Map<String, RelayContact>> data = null;


             // Now create a new list adapter bound to the cursor.
             // SimpleListAdapter is designed for binding to a Cursor.
             ListAdapter adapter = new SimpleAdapter(this, data, 0, new String[] {"First", "Number"}, new int[] {android.R.id.text1, android.R.id.text2});  // Parallel array of which template objects to bind to those columns.

             // Bind to our new adapter.
             this.setListAdapter(adapter);*/
}

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }




}

這是我自定義的HttpRequest AsyncTask類

package com.dd.relay;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import android.os.AsyncTask;

public class HttpRequest extends AsyncTask<URL, Void, Void> {

    protected String doInBackground(URL url) throws Exception {

          HttpURLConnection conn = (HttpURLConnection) url.openConnection();


          if (conn.getResponseCode() != 200) {
            throw new IOException(conn.getResponseMessage());
          }

          // Buffer the result into a string
          BufferedReader rd = new BufferedReader(
              new InputStreamReader(conn.getInputStream()));
          StringBuilder sb = new StringBuilder();
          String line;
          while ((line = rd.readLine()) != null) {
            sb.append(line);
          }
          rd.close();

          conn.disconnect();
        return sb.toString();


    }

    protected void onProgressUpdate(Integer progress) {

    }

    protected void onPostExecute(String result) {
      System.out.println(result);
    }

    @Override
    protected Void doInBackground(URL... arg0) {
        // TODO Auto-generated method stub
        return null;
    }


}

Android不允許在UI線程上進行網絡通信。 Android提供了一個名為AsyncTask的類,用於此類交互。 有關詳細信息和解決方案的一個選項,請參閱此鏈接(這可能是您想要的):

如何修復android.os.NetworkOnMainThreadException?

或者您也可以創建一個自定義類來擴展Thread或實現Runnable ,它使用Handler發布到UI線程

試試這個鏈接希望對你充分利用: -

通過http get:Android驗證登錄詳細信息

public class LongOperation extends AsyncTask<String, Void, String> {

        @Override
        protected String doInBackground(String... params) {
               // call function 
                login(userName, password);
                return null;
        }        

        @Override
        protected void onPostExecute(String result) {             
        }

        @Override
        protected void onPreExecute() {
        }

        @Override
        protected void onProgressUpdate(Void... values) {
        }
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM