我正试图从Android应用中获取JSONObject
但是却崩溃了
response = httpclient.execute(httpget)
并提出异常。
我认为问题是网址编码,但我不确定。如果我没有对网址进行编码,则应用会在httpget = new HttpGet(encodeURL)
上面几行崩溃。
我传递的网址是:http://api.elpais.com/ws/LoteriaNavidadPremiados?n=99999
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
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.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
public class Json {
public Json(){
}
public static JSONObject getJson(String url) {
String encodeUrl = null;
InputStream is = null;
String result = "";
JSONObject jsonObject = null;
HttpGet httpget;
// Encode URL. If not, HttpGet will crash
try {
encodeUrl = URLEncoder.encode(url, "UTF-8");
//encodeUrl = encodeUrl.replaceAll("%3F", "?"); // I tried replacing this but does not work
//encodeUrl = encodeUrl.replaceAll("%3D", "="); //
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
Log.d("LOG_EXCEPTION", "Unsuported Encoding Exception");
e1.printStackTrace();
}
// HTTP
try {
HttpClient httpclient = new DefaultHttpClient(); // for port 80
// requests!
httpget = new HttpGet(encodeUrl);
// HttpPost httppost = new HttpPost(url);
Log.d("LOG", "THIS CODE I SEE in LOGCAT");
HttpResponse response = httpclient.execute(httpget); // HERE CRASH
Log.d("LOG", "THIS CODE I DO NOT SEE in LOGCAT");
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (IOException e) {
Log.d("LOG_EXCEPTION", "IOException");
} catch (IllegalArgumentException e) {
Log.d("LOG_EXCEPTION", "URL no valida");
} catch (Exception e) {
// return null;
Log.d("LOG_EXCEPTION", "Exception");
}
// Read response to string
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "utf-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
} catch (Exception e) {
Log.d("LOG_EXCEPTION", "Reader response to string");
// return null;
}
// Convert string to object
try {
jsonObject = new JSONObject(result);
} catch (JSONException e) {
// return null;
}
return jsonObject;
}
}
和日志:
12-01 11:04:01.336: D/(1631): HostConnection::get() New Host Connection established 0xb8d029d0, tid 1631
12-01 11:04:05.866: D/LOG(1631): http%3A%2F%2Fapi.elpais.com%2Fws%2FLoteriaNavidadPremiados?n=99999
12-01 11:04:05.866: D/LOG(1631): httpget work fine
12-01 11:04:06.176: D/LOG_EXCEPTION(1631): Exception
12-01 11:04:06.176: D/LOG_EXCEPTION(1631): Reader response to string
12-01 11:04:06.176: D/AndroidRuntime(1631): Shutting down VM
12-01 11:04:06.186: W/dalvikvm(1631): threadid=1: thread exiting with uncaught exception (group=0xb1a5bb90)
12-01 11:04:06.186: E/AndroidRuntime(1631): FATAL EXCEPTION: main
12-01 11:04:06.186: E/AndroidRuntime(1631): Process: com.example.loterianavidad, PID: 1631
12-01 11:04:06.186: E/AndroidRuntime(1631): java.lang.NullPointerException
12-01 11:04:06.186: E/AndroidRuntime(1631): at com.example.loterianavidad.MainActivity$2.onClick(MainActivity.java:86)
12-01 11:04:06.186: E/AndroidRuntime(1631): at android.view.View.performClick(View.java:4424)
12-01 11:04:06.186: E/AndroidRuntime(1631): at android.view.View$PerformClick.run(View.java:18383)
12-01 11:04:06.186: E/AndroidRuntime(1631): at android.os.Handler.handleCallback(Handler.java:733)
12-01 11:04:06.186: E/AndroidRuntime(1631): at android.os.Handler.dispatchMessage(Handler.java:95)
12-01 11:04:06.186: E/AndroidRuntime(1631): at android.os.Looper.loop(Looper.java:137)
12-01 11:04:06.186: E/AndroidRuntime(1631): at android.app.ActivityThread.main(ActivityThread.java:4998)
12-01 11:04:06.186: E/AndroidRuntime(1631): at java.lang.reflect.Method.invokeNative(Native Method)
12-01 11:04:06.186: E/AndroidRuntime(1631): at java.lang.reflect.Method.invoke(Method.java:515)
12-01 11:04:06.186: E/AndroidRuntime(1631): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:777)
12-01 11:04:06.186: E/AndroidRuntime(1631): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:593)
12-01 11:04:06.186: E/AndroidRuntime(1631): at dalvik.system.NativeStart.main(Native Method)
MainActivity相关代码:
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Context context = getApplicationContext();
CharSequence text = "Accediendo a la base de datos...";
JSONObject j = Json.getJson("http://api.elpais.com/ws/LoteriaNavidadPremiados?n=99999");
Log.d("LOG", j.toString()); // HERE is LINE 87
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
String prem = "hola";
答案 0 :(得分:1)
目前,您正在使用参数对整个网址进行编码,因此只需编码参数,然后在传递给HttpGet
构造函数之前附加到网址:
String str_url="99999";
encodeUrl = URLEncoder.encode(url, "UTF-8");
String final_url="http://api.elpais.com/ws/LoteriaNavidadPremiados?n="+encodeUrl;
答案 1 :(得分:0)
您的应用在MAINACTIVITY
中的行号87
上崩溃了
java.lang.NullPointerException 12-01 10:25:08.546: E/AndroidRuntime(1428): at com.example.loterianavidad.MainActivity$2.onClick(MainActivity.java:87)
因为你在一个按钮上使用了onclicklistener
,而该按钮在MAINACTIVITY的引用XML视图中不存在