簡體   English   中英

Android中的Json:位置0處出現意外字符(<)

[英]Json in Android : Unexpected character (<) at position 0

我正在嘗試將Json用於android在線數據庫連接。 問題是無論我嘗試什么,我都會在位置0錯誤中得到越來越流行的意外字符(<)。

這是我的方法:

 public void getData(){
    String result = "";
    InputStream isr = null;

    try{
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost("http:link to my file.php");
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity entity = response.getEntity();
        isr = entity.getContent();
    }
    catch(Exception e){
        Log.e("log_tag", "Error in http connection " + e.toString());
        resulString="Couldn't connect to database";
    }
    //convert response to string
    try{
        BufferedReader reader = new BufferedReader(newInputStreamReader(isr,"iso-8859-1"),8);
        StringBuilder sb = new StringBuilder();

        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        isr.close();

        result=sb.toString();
    }
    catch(Exception e){
        Log.e("log_tag", "Error  converting result "+e.toString());
    }

    //parse json data
    try {
        String s = "";
        JSONParser parser_obj = new JSONParser();
        JSONArray jArray = (JSONArray) parser_obj.parse(result.toString());

        for(int i=0; i<jArray.length();i++){
            JSONObject json = jArray.getJSONObject(i);
            s = s +
                    "Id : "+json.getInt("Id")+" Name: "+json.getString("ShopName")+"\n"+
                    "Icon : "+json.getInt("ShopIcon")+"Description:"+json.getString("ShopDesc")+"\n\n";
        }

        resulString=s;

    } catch (Exception e) {
        // TODO: handle exception
        Log.e("log_tag", "Error Parsing Data "+e.toString());
    }

}

嘗試了get和post方法,這是我的php文件:

php 1

連接已建立,但沒有結果,loggcat顯示該錯誤。 你能幫我嗎?

2天后,我終於找到了解決方案:只需添加以下2個標頭:

 request.setHeader("Accept", "application/json"); // or application/jsonrequest
 request.setHeader("Content-Type", "application/json");

還要確保HTTP中的網址是完美的。

這對於測試連接很有幫助: http : //www.requestmaker.com

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM