package com.jouhu;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class PHPJsonActivity extends Activity {
/** Called when the activity is first created. */
private String Tag = "PHPJsonActivity";
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//EditText edit = (EditText)findViewById(R.id.editText1);
//String url = "http://88.88.88.200:8888/phpjson/index.php?type=1";
//getServerJsonDataWithNoType(url,edit);
Button btn = (Button)findViewById(R.id.button1);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
EditText edit = (EditText)findViewById(R.id.editText1);
String url = "http://88.88.88.200:8888/phpjson/index.php?type=1";
getServerJsonDataWithNoType(url,edit);
}
});
}
public void getServerJsonDataWithNoType(String url,EditText editText)
{
int res = 0;
HttpClient client = new DefaultHttpClient();
StringBuilder str = new StringBuilder();
HttpGet httpGet = new HttpGet(url);
try
{
HttpResponse httpRes = client.execute(httpGet);
httpRes = client.execute(httpGet);
res = httpRes.getStatusLine().getStatusCode();
if(res == 200)
{
BufferedReader buffer = new BufferedReader(new InputStreamReader(httpRes.getEntity().getContent()));
for(String s = buffer.readLine(); s != null ; s = buffer.readLine())
{
str.append(s);
}
//String out = EntityUtils.toString(httpRes.getEntity().getContent(), "UTF-8");
//StringBuilder sb = new StringBuilder()
Log.i(Tag,str.toString());
try
{
//JSONObject json = new JSONObject(str.toString()).getJSONObject("content");
JSONObject json = new JSONObject(str.toString());
String title = json.getString("title");
Log.i(Tag,title);
int id = json.getInt("id");
String value = json.getString("value");
Log.i(Tag,value);
editText.setText("Title:" + title + " ID:" + id + " Value:" + value);
}
catch(JSONException e)
{
Log.i(Tag, e.getLocalizedMessage());
//buffer.close();
e.printStackTrace();
}
}
else
{
Log.i(Tag, "HttpGet Error");
}
}
catch(Exception e)
{
Log.i(Tag, "Exception");
}
}
}
1 出现Value of type java.lang.String cannot be converted to JSONObject.这是由于我们的php或者其他服务器脚本有BOM头造成的。可以通过Editplus或者EmEditor或者UltraEditor进行删除。具体可以参考如何用去掉UTF-8的BOM头