0

我正在尝试向我的本地 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;
    }


}
4

2 回答 2

2

Android 不允许在 UI 线程上进行网络通信。Android 提供了一个AsyncTask用于此类交互的类。有关详细信息和解决方案的一个选项,请参阅此链接(这可能是您想要的):

如何修复 android.os.NetworkOnMainThreadException?

或者您也可以创建一个自定义类,Thread该类Runnable使用Handler

于 2013-07-20T18:56:50.410 回答
0

试试这个链接希望对你有用:-

通过 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) {
        }
    }
于 2013-07-20T19:04:11.597 回答