[英]HTTPGet works in Java but not Android
我在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 vm Internet瀏覽器和本地筆記本電腦訪問它。
我也有麻煩找到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();
}
}
另外,如果您聽不清,我也想在單擊按鈕時撥打電話。
您不能在主線程上進行網絡調用。 嘗試將網絡呼叫放入AsyncTask的doInBackground
中:
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();
}
使用Android時,不允許在主線程上進行網絡調用。 奇怪的是,這里似乎沒有出現這樣的問題。 您正在使用單獨的線程還是AsyncTask?
您能發布Android代碼嗎? 因為這看起來像純Java。 另外,Android可能會出錯。 確保清單文件中具有適當的權限。 然后,您需要使用后台任務從網絡實際檢索某些內容。 這可以通過擴展Asynctask抽象類來完成。
檢查文檔:
http://developer.android.com/reference/android/os/AsyncTask.html
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.