gpt4 book ai didi

java - 尝试发送到 JSON 时,应用程序在 HttpResponse 响应 = httpclient.execute(httpget) 上崩溃

转载 作者:行者123 更新时间:2023-12-01 13:46:45 25 4
gpt4 key购买 nike

我尝试从 Android 应用获取 JSONObject 但崩溃了
response = httpclient.execute(httpget) 并引发异常。

我认为问题出在 url 编码上,但我不确定。如果我不编码 URL,应用程序会在 httpget = new HttpGet(encodeURL) 上的几行崩溃。

我传递的URL是: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";

最佳答案

目前,您正在使用参数对整个 url 进行编码,因此只需对参数进行编码,然后在传递给 HttpGet 构造函数之前附加到 url,如下所示:

String str_url="99999";
encodeUrl = URLEncoder.encode(url, "UTF-8");
String final_url="http://api.elpais.com/ws/LoteriaNavidadPremiados?n="+encodeUrl;

关于java - 尝试发送到 JSON 时,应用程序在 HttpResponse 响应 = httpclient.execute(httpget) 上崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20313918/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com