HTTPGet适用于Java但不适用于Android

时间:2013-07-30 21:20:59

标签: java android mobile httpclient

我在Android工作,我遇到了一大堆代码问题:

public static void main(String[] args) {
    HttpClient httpClient = new DefaultHttpClient();
    HttpContext localContext = new BasicHttpContext();
    HttpGet httpGet = new HttpGet("http://9.42.68.71:8080/resources/dashboard?dashboard=rack");
    String text = null;
    try {
          HttpResponse response = httpClient.execute(httpGet, localContext);
          HttpEntity entity = response.getEntity();
          text = getASCIIContentFromEntity(entity);
    } catch (Exception e) {
    }
    System.out.println(text);
}

这段代码在Java中的不同项目上正确运行。问题是,当我尝试在Android中使用这一块代码时,它会出错。

FATAL EXCEPTION: main
java.lang.IllegalStateException: Could not execute method of the activity
at android.view.View$1.onClick(View.java:3633)
at android.view.View.performClick(View.java:4240)
at android.view.View$PerformClick.run(View.java:17721)
at android.os.Handler.handleCallback(Handler.java:730)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5103)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at android.view.View$1.onClick(View.java:3628)
... 11 more
Caused by: java.lang.NullPointerException
at com.android.internal.os.LoggingPrintStream.println(LoggingPrintStream.java:298)
at com.example.mgen.MgenActivity.renew(MgenActivity.java:61)
at com.example.mgen.MgenActivity.refresh(MgenActivity.java:44)
... 14 more

我在两个项目上都有相同的导入。有没有人看到像这样的问题或像这样的例外?我似乎无法在任何地方找到类似的东西。

此外,我有一个VPN进入本地9.网络,我可以从Android虚拟机互联网浏览器和我的本地笔记本电脑访问它。

我也有麻烦找到Android版本上的问题就行了

HttpResponse response = httpClient.execute(httpGet, localContext);

更完整的代码:

package com.example.mgen;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class MgenActivity extends Activity {
ArrayList<mgenObject> listItems = new ArrayList<mgenObject>();

ArrayAdapter<mgenObject> adapter;

public void onCreate(Bundle icicle) {
    super.onCreate(icicle);
    setContentView(R.layout.main);

    adapter = new ArrayAdapter<mgenObject>(this,
            android.R.layout.simple_list_item_1, listItems);
    ListView lv = (ListView) findViewById(R.id.list);
    lv.setAdapter(adapter);
    renew();
}

// METHOD WHICH WILL HANDLE DYNAMIC INSERTION
public void refresh(View v) {

    listItems = renew();
    adapter.notifyDataSetChanged();

    System.out.println("refresh worked");
}

public ArrayList<mgenObject> renewTest() {
    mgenObject object = new mgenObject("test", "test", "test");
    ArrayList<mgenObject> list = new ArrayList<mgenObject>();
    list.add(object);
    return list;

}

public ArrayList<mgenObject> renew() {
    ArrayList<mgenObject> tempList = new ArrayList<mgenObject>();
    String jsonStr = getMgenJSON();
    System.out.println(jsonStr);

    try {
        JSONArray rows = new JSONArray(jsonStr); // Parse the JSON to a
                                                    // JSONArray
        for (int i = 0; i < rows.length(); i++) { // Loop over each each row
            JSONObject element = rows.getJSONObject(i); // Get row object
            String workflow = element.getString("workflow_state");
            String vgen = element.getString("vgen_state");
            String name = element.getString("title");

            mgenObject tempObject = new mgenObject(name, workflow, vgen);
            tempList.add(tempObject);
        }

    } catch (JSONException e) {
        // JSON Parsing error
        e.printStackTrace();
    }

    return tempList;
}

public String getMgenJSON() {
    HttpClient httpClient = new DefaultHttpClient();
    HttpContext localContext = new BasicHttpContext();
    HttpGet httpGet = new HttpGet(
            "http://9.42.68.71:8080/resources/dashboard?dashboard=rack");
    String text = null;
    try {
        System.out.println("testing3");
        HttpResponse response = httpClient.execute(new HttpGet("http://9.42.68.71:8080/resources/dashboard?dashboard=rack"));
        System.out.println("testing3.5");
        HttpEntity entity = response.getEntity();
        System.out.println("testing4");
        text = getASCIIContentFromEntity(entity);
        System.out.println("testing5");
    } catch (Exception e) {
        return e.getLocalizedMessage();
    }
    System.out.println(text);
    return text;
}

protected String getASCIIContentFromEntity(HttpEntity entity)
        throws IllegalStateException, IOException {
    InputStream in = entity.getContent();
    StringBuffer out = new StringBuffer();
    int n = 1;
    while (n > 0) {
        byte[] b = new byte[4096];
        n = in.read(b);
        if (n > 0)
            out.append(new String(b, 0, n));
    }
    return out.toString();
}
}

此外,如果您无法分辨,我会在点击按钮时尝试拨打此电话。

3 个答案:

答案 0 :(得分:1)

您无法在主线程上进行网络呼叫。尝试将您的网络电话放入AsyncTaskdoInBackground

public void blah(String[] args) {
   new AsyncTask<Void, Void, Void>() {

        @Override
        protected void onPreExecute()
        {
            // here is for code you do before the network call. you 
            // leave it empty
        }

        @Override
        protected Void doInBackground(Void... params)
        {
            // here goes your network call
            HttpClient httpClient = new DefaultHttpClient();
            HttpContext localContext = new BasicHttpContext();
            HttpGet httpGet = new HttpGet("http://9.42.68.71:8080/resources/dashboard?dashboard=rack");
            String text = null;
            try {
                  HttpResponse response = httpClient.execute(httpGet, localContext);
                  HttpEntity entity = response.getEntity();
                  text = getASCIIContentFromEntity(entity);
            } catch (Exception e) {
            }
            System.out.println(text);
        }

        @Override
        protected void onPostExecute(Void res)
        {
            // here goes your UI code. i.e if you want to hide a button
        }
    }.execute();
}

答案 1 :(得分:0)

使用Android时,主线程上不允许进行网络调用。奇怪的是,这似乎不是在这里提出的问题。您是在处理单独的线程还是AsyncTask?

答案 2 :(得分:0)

请您发布Android代码吗?因为这看起来像普通的Java。 Android中还有很多可能出错的地方。确保您在清单文件中具有适当的权限。然后,您需要使用后台任务来实际从网络中检索某些内容。这可以通过扩展Asynctask抽象类来完成。

查看文档:

http://developer.android.com/reference/android/os/AsyncTask.html