将接收以下json,但通过http://localhost/getData.php会引发异常

{"username":"not found","password":null}


我收到的日志

02-19 17:31:54.745: E/JSON Parser(5277): Error parsing data org.json.JSONException: End of input at character 0 of
02-19 17:31:59.185: E/JSON Parse(5277): ERROR


以下代码是引发异常的方法

@Override
    protected String doInBackground(String... url){

        try{
            String resultText = "";
            EditText edit = (EditText)findViewById(R.id.text_box);
            id = edit.getText().toString();
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("id",id));

            JSONObject json = jsonParser.HttpRequest("http://localhost/getData.php", params);

            resultText = json.getString("username");



        }catch(Exception e){
            e.printStackTrace();
            Log.e("JSON Parse","ERROR");
        }

        return "";
    }


公共类SimpleJsonParser {

public SimpleJsonParser(){

}


public JSONObject HttpRequest(String url, List<NameValuePair> params){
    InputStream input = null;
    JSONObject jObj = null;
    String json = "";
    String line;

    StringBuilder builder = new StringBuilder();
    HttpClient client = new DefaultHttpClient();
    paramsString = URLEncodedUtils.format(params,"utf-8");
    url += "?" + paramsString;
    HttpGet httpGet = new HttpGet(url);


    try{


        HttpResponse response = client.execute(httpGet);
        StatusLine statusLine = response.getStatusLine();

        if(statusLine.getStatusCode() == HttpStatus.SC_OK){
            HttpEntity entity = response.getEntity();
            input = entity.getContent();
            BufferedReader reader =
                    new BufferedReader(new InputStreamReader(input));


            while((line = reader.readLine())!=null){
                builder.append(line);
            }
            json = builder.toString();

        } else {
            Log.e("JSON Parser","Failed to download file");
        }
    }catch(ClientProtocolException e){
        e.printStackTrace();
    }catch(IOException e){
        e.printStackTrace();
    }

    try {
        jObj = new JSONObject(json);
        input.close();
    } catch (Exception e) {
        Log.e("JSON Parser", "Error parsing data " + e.toString());
    }

    return jObj;
}


}

我的代码有问题吗?我提供的代码是发生异常引发的地方

最佳答案

从您提到的内容来看,您似乎正在通过仿真器执行此操作。

仿真器可能无法访问http://localhost//。您可以尝试使用回送地址或IP地址进行访问。

关于java - 从JSON和org.json.JSON中获取数据,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/14963993/

10-11 22:21
查看更多