我想使用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();
}
}
}
}
}
请指出我,我的错误代码在哪里..
答案 0 :(得分:0)
请原谅我的英语...... 我不确定问题是什么..但我可以建议你
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");
尝试在这里使用这样的状态和代码从Web服务返回。
答案 1 :(得分:0)
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();
}
答案 2 :(得分:0)
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