【问题标题】:Making Json request to php mysql through android通过android向php mysql发出Json请求
【发布时间】:2013-12-02 12:17:13
【问题描述】:

我想使用json请求从android中搜索mysql,谷歌提供了这段代码,但我在这段代码中遇到了这个问题,我不知道我哪里出错了......

Error parsing data org.json.JSONException: Value <?xml of type java.lang.String cannot be converted to JSONArray

这是我的主要活动..

public class JSONUseActivity extends Activity {

    EditText byear;   // To take birthyear as input from user
    Button submit;    
    TextView tv;      // TextView to show the result of MySQL query 

     String returnString;   // to store the result of MySQL query after decoding JSON

        /** Called when the activity is first created. */

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
                .detectDiskReads().detectDiskWrites().detectNetwork().penaltyLog().build()); 
        // StrictMode is most commonly used to
                                                                        // catch
                                                                        // accidental
                                                                        // disk
                                                                        // or
                                                                        // network
                                                                        // access
                                                                        // on
                                                                        // the
                                                                        // application's
                                                                        // main
                                                                        // thread

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_jsonuse);

        byear = (EditText) findViewById(R.id.editText1);
        submit = (Button) findViewById(R.id.submitbutton);
        tv = (TextView) findViewById(R.id.showresult);

     // define the action when user clicks on submit button
        submit.setOnClickListener(new View.OnClickListener(){        
         public void onClick(View v) {
          // declare parameters that are passed to PHP script i.e. the name "birthyear" and its value submitted by user   
          ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();

          // define the parameter
          postParameters.add(new BasicNameValuePair("birthyear",byear.getText().toString()));
          String response = null;

          // call executeHttpPost method passing necessary parameters 
          try {
              response = CustomHttpClient.executeHttpPost("http://10.0.2.2/jsonscript.php",postParameters);

  // store the result returned by PHP script that runs MySQL query
     String result = response.toString();   

      //parse json data
         try{
                 returnString = "";

                 JSONObject mainObject=new JSONObject();
                // JSONArray dataArray=new JSONArray();

                 //dataArray=mainObject.getJSONArray("Table");

                 //JSONArray jArray = mainObject.getJSONArray(result);
                 JSONArray jArray = new JSONArray(result);

                 for(int i=0;i<jArray.length();i++){

                     JSONObject json_data = jArray.getJSONObject(i);

                     Log.i("log_tag","id: "+json_data.getInt("id")+
                             ", name: "+json_data.getString("name")+
                             ", sex: "+json_data.getInt("sex")+
                             ", birthyear: "+json_data.getInt("birthyear") );
                     //Get an output to the screen                        
                     returnString += "\n" + json_data.getString("name").toString() + " -> "+ json_data.getString("birthyear").toString();
                     }
                 }
         catch(JSONException e){
             Log.e("Json_log_tag", "Error parsing data "+e.toString());
             }
         try{
             tv.setText(returnString);
             }
         catch(Exception e){
             Log.e("log_tag","Error in Display!" + e.toString());
             }   
         }
          catch (Exception e) {
              Log.e("log_tag","Error in http connection!!" + e.toString());
              }
          }
         }); 
        }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.jsonuse, menu);
        return true;
    }

}

第二个活动。

public class CustomHttpClient {


    /** The time it takes for our client to timeout */

     public static final int HTTP_TIMEOUT = 30 * 1000; // milliseconds


     /** Single instance of our HttpClient */

     private static HttpClient mHttpClient;


     /**

      * Get our single instance of our HttpClient object.

      * 

      * @return an HttpClient object with connection parameters set

      */

     private static HttpClient getHttpClient() {
         if (mHttpClient == null) {
             mHttpClient = new DefaultHttpClient();
             final HttpParams params = mHttpClient.getParams();
             HttpConnectionParams.setConnectionTimeout(params, HTTP_TIMEOUT);
             HttpConnectionParams.setSoTimeout(params, HTTP_TIMEOUT);
             ConnManagerParams.setTimeout(params, HTTP_TIMEOUT);
             }
         return mHttpClient;
         }


     /**

      * Performs an HTTP Post request to the specified url with the specified

      * parameters.

      * 

      * @param url

      *            The web address to post the request to

      * @param postParameters

      *            The parameters to send via the request

      * @return The result of the request

      * @throws Exception

      */

     public static String executeHttpPost(String url,ArrayList<NameValuePair> postParameters) throws Exception {
         BufferedReader in = null;
         try {

             HttpClient client = getHttpClient();
             HttpPost request = new HttpPost(url);

             UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(postParameters);
             request.setEntity(formEntity);

             HttpResponse response = client.execute(request);

             in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

             StringBuffer sb = new StringBuffer("");
             String line = "";
             String NL = System.getProperty("line.separator");

             while ((line = in.readLine()) != null) {               
                 sb.append(line + NL);
                 }

             in.close();             
             String result = sb.toString();

             return result;

             } finally {
                 if (in != null) {
                     try {
                         in.close();
                         } catch (IOException e) {
                             Log.e("log_tag", "Error converting result "+e.toString());
                             e.printStackTrace();
                             }
                     }
                 }
         }


     /**

      * Performs an HTTP GET request to the specified url.

      * 

      * @param url

      *            The web address to post the request to

      * @return The result of the request

      * @throws Exception

      */

     public static String executeHttpGet(String url) throws Exception {

      BufferedReader in = null;

      try {
          HttpClient client = getHttpClient();
          HttpGet request = new HttpGet();
          request.setURI(new URI(url));
          HttpResponse response = client.execute(request);

          in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

          StringBuffer sb = new StringBuffer("");
          String line = "";
          String NL = System.getProperty("line.separator");
          while ((line = in.readLine()) != null) {
              sb.append(line + NL);
              }
          in.close();
          String result = sb.toString();
          return result;
          } finally {
              if (in != null) {
                  try {
                      in.close();
                      } catch (IOException e) {
                          Log.e("log_tag", "Error converting result "+e.toString());
                          e.printStackTrace();
                          }
                  }
              }
      }
     }

请指出我在哪里得到错误的代码..

【问题讨论】:

  • 您尝试解析的数据不是 JSON,而是 XML。确保您使用请求访问的服务器返回 JSON。

标签: php android mysql json


【解决方案1】:

请原谅我的英语... 我不确定是什么问题.. 但我可以建议你

String result = response.toString();    

这里你将结果作为字符串但是

 JSONArray jArray = new JSONArray(result);

但在这里您将 String 传递给 JSONArray。这导致了错误......

这样试试

String  responseBodyFH = EntityUtils.toString((HttpEntity) response);
    JSONObject jObj = new JSONObject(responseBodyFH);
    String status = jObj.getString("status");
    String code = jObj.getString("code");

尝试像这样在这里使用状态和代码正在从网络服务返回。

【讨论】:

    【解决方案2】:
        try {
                HttpClient httpclient=new DefaultHttpClient();
                HttpPost httppost=new HttpPost("http://192.168.10.104/phpweb/phpresponse.php");
                HttpResponse httpResponse=httpclient.execute(httppost);
            //  content=EntityUtils.toString(httpResponse.getEntity());
                HttpEntity httpentity=httpResponse.getEntity();
                is=httpentity.getContent();
                BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
                StringBuilder sb = new StringBuilder();
    
                while((line = reader.readLine()) != null) {
    
                    sb.append(line + "\n");
                    singlecolumn.add(line);
    
    
                }
    
                is.close();
                result = sb.toString(); 
                System.out.println("=========result"+result);
    
    
    
    
                JSONArray json=new JSONArray(result);
                  JSONObject jo = null;
    
                  list1=new String[json.length()];
                  list2=new String[json.length()];
    
                for(int i=0; i<json.length(); i++) {
    
                    jo = json.getJSONObject(i);
                    list1[i] = jo.getString("studentname");
                    list2[i] =  jo.getString("sno");
    
                System.out.println("######"+list1[i]);
    
    
    
                }
            } catch (ClientProtocolException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
    

    【讨论】:

    • 代码不工作。使用 post 方法向 localhost 请求任何简单的方法。
    【解决方案3】:
    simple way to get http response from server
    
      HttpClient httpclient = new DefaultHttpClient();
      HttpPost httppost = new HttpPost("http://www.codeincloud.tk/First.php");
      HttpResponse response = httpclient.execute(httppost);
      String str =  EntityUtils.toString(response.getEntity());
    

    如果您有任何疑问,请关注 http://codeoncloud.blogspot.in/2012/07/android-php-web-service-client.html sampleprogramz.com

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-01-03
      • 2017-04-15
      • 1970-01-01
      • 2017-09-14
      • 2014-07-28
      • 2020-11-30
      • 2021-05-19
      • 1970-01-01
      相关资源
      最近更新 更多