【问题标题】:org.json.JSONException: End of input at character 0 oforg.json.JSONException:在字符 0 处输入结束
【发布时间】:2025-12-03 13:30:02
【问题描述】:

我已按照以下教程进行操作,但我的代码出现系统错误: http://www.informit.com/articles/article.aspx?p=2154675&seqNum=4

以下是所有错误:

W/EGL_emulation:eglSurfaceAttrib 未实现 W/OpenGLRenderer:无法在表面 0x7f651f4e3780 上设置 EGL_SWAP_BEHAVIOR,错误 = EGL_SUCCESS W/DefaultRequestDirector:身份验证错误:无法响应任何这些质询:{} W/System.err: org.json.JSONException: 在字符 0 处输入结束 W/System.err:在 org.json.JSONTokener.syntaxError(JSONTokener.java:450) W/System.err:在 org.json.JSONTokener.nextValue(JSONTokener.java:97) W/System.err:在 org.json.JSONObject.(JSONObject.java:156) W/System.err:在 org.json.JSONObject.(JSONObject.java:173) W/System.err:在 com.example.theol.opsc7312_assign2_14001515_theolin_naidoo.MainActivity$ReadJSONFeed.onPostExecute(MainActivity.java:74) W/System.err:在 com.example.theol.opsc7312_assign2_14001515_theolin_naidoo.MainActivity$ReadJSONFeed.onPostExecute(MainActivity.java:46) W/System.err:在 android.os.AsyncTask.finish(AsyncTask.java:636) W/System.err:在 android.os.AsyncTask.access$500(AsyncTask.java:177) W/System.err:在 android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:653) W/System.err:在 android.os.Handler.dispatchMessage(Handler.java:102) W/System.err:在 android.os.Looper.loop(Looper.java:135) W/System.err:在 android.app.ActivityThread.main(ActivityThread.java:5254) W/System.err:在 java.lang.reflect.Method.invoke(Native Method) W/System.err:在 java.lang.reflect.Method.invoke(Method.java:372) W/System.err:在 com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903) W/System.err:在 com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698) 应用程序终止。

这是我的代码:

import android.os.Bundle;
import android.app.Activity;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.view.View;
import org.apache.http.client.methods.HttpPost;
import org.json.JSONException;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.client.HttpClient;
import org.apache.http.HttpResponse;
import org.apache.http.HttpEntity;
import java.io.InputStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import android.os.AsyncTask;
import org.json.JSONObject;
import org.apache.http.StatusLine;
import org.json.JSONArray;
import java.text.NumberFormat;

public class MainActivity extends Activity {
    String city="";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button submitButton = (Button)this.findViewById(R.id.submit_btn);

        submitButton.setOnClickListener(new Button.OnClickListener(){
            public void onClick(View v) {
                String country="";
                EditText cityName = (EditText) findViewById(R.id.city_name);
                city=cityName.getText().toString();

                String url="http://api.openweathermap.org/data/2.5/weather?q="+city;
                new ReadJSONFeed().execute(url);

            }
        });
    }
    private class ReadJSONFeed extends AsyncTask<String, String, String> {
        protected void onPreExecute() {}
        @Override
        protected String doInBackground(String... urls) {
            HttpClient httpclient = new DefaultHttpClient();
            StringBuilder builder = new StringBuilder();
            HttpPost httppost = new HttpPost(urls[0]);
            try {
                HttpResponse response = httpclient.execute(httppost);
                StatusLine statusLine = response.getStatusLine();
                int statusCode = statusLine.getStatusCode();
                if (statusCode == 200) {
                    HttpEntity entity = response.getEntity();
                    InputStream content = entity.getContent();
                    BufferedReader reader = new BufferedReader(new InputStreamReader(content));
                    String line;
                    while ((line = reader.readLine()) != null) {
                        builder.append(line);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return builder.toString();
        }
        protected void onPostExecute(String result) {
            String weatherInfo="Weather Report of "+city +" is: \n";
            try{

                JSONObject jsonObject = new JSONObject(result);
                JSONObject jscoordObject = new JSONObject(jsonObject.getString("coord"));
                weatherInfo+="Longitude: "+jscoordObject.getString("lon")+"\n";
                weatherInfo+="Latitude: "+jscoordObject.getString("lat")+"\n";
                JSONArray jsweatherObject = new JSONArray(jsonObject.getString("weather"));
                JSONObject jweatherObject = jsweatherObject.getJSONObject(0);
                weatherInfo+="Clouds: "+jweatherObject.getString("description")+"\n";
                JSONObject jsmainObject = new JSONObject(jsonObject.getString("main"));
                weatherInfo+="Humidity: "+jsmainObject.getString("humidity")+"% \n";
                weatherInfo+="Atmospheric Pressure: "+jsmainObject.getString("pressure")+"hPa \n";
                float temp=Float.parseFloat(jsmainObject.getString("temp"));
                temp = temp - (float) 273.15;
                NumberFormat df = NumberFormat.getNumberInstance();
                df.setMaximumFractionDigits(2);
                weatherInfo+="Temperature: "+ String.valueOf(df.format(temp)) +" C\n";
                JSONObject jswindObject = new JSONObject(jsonObject.getString("wind"));
                weatherInfo+="Wind Speed: "+jswindObject.getString("speed")+"mps \n";
            }
            catch (JSONException e) {
                e.printStackTrace();
            }
            TextView resp = (TextView) findViewById(R.id.response);
            if(weatherInfo.trim().length() >0 )
                resp.setText(weatherInfo);
            else
                resp.setText("Sorry no match found");
        }
    }
}

【问题讨论】:

  • 记录结果的值,请在尝试解析之前记录它
  • 那个代码也很老了。 Apache HTTP 已弃用,我认为 openweather api 需要 API 密钥
  • 在 URL 字符串中,添加密钥。我相信他们的文档显示了示例 URL。不过,我建议您找一个不同的、更新的教程
  • 我看过这个页面:informit.com/articles/article.aspx?p=2154675,上面写着“OpenWeatherMap 服务提供免费的天气数据和预报 API。用户提供城市和国家信息后,Web 服务返回当前JSON 格式数据中的天气信息。使用以下语法访问 Web 服务:api.openweathermap.org/data/2.5/…" 所以我看不到 API 的去向。我知道这已经过时了,但我真的很想尝试让它发挥作用。
  • 根据您发送的链接,它应该是这样的 "String url="http://api.openweathermap .org/data/2.5/weather?q="+city&APPID=b58687dbd22bdbecc0b26c18c46597ab ;"但它给出了一个错误。知道如何解决这个问题吗?我在链接中添加了空格,以便您查看。

标签: java android json android-asynctask


【解决方案1】:

根据错误,您没有返回 JSON,这可能意味着您遇到了一些 HTTP 错误。

如果您在尝试解析之前Log result 的值,您可以更容易地看到它。


但是,您应该注意这一点。

“如果您使用免费或付费计划,要访问 API,您需要注册一个 API 密钥。”
- http://openweathermap.org/api

看这里use the API key

换句话说,获取一个 API 密钥,然后将其附加到您的 URL。例如

String API_KEY = "XXXXxxxx";
String url = "http://.../weather?q=" + city + "&APPID=" + API_KEY;

【讨论】:

  • 按照@cricket_007 所说的进行修复。谢谢好心的先生!