我需要包括JSON在我的Android應用程序, 我按照一些教程,並安裝了該應用從Twitter讀取測試Android的JSON Web服務問題
package com.or.jsonswitch;
import ***
public class JsonTestMySwitchActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Log.d("msg", "app started 1");
String readResponse = readResponse(); //crea un string llenado por lo que devuelve la funcion()
try {
JSONArray jsonArray = new JSONArray(readResponse);
Log.d("msg", "number of entries::"+jsonArray.length());
Log.d("msg", "response::"+jsonArray);
} catch (Exception e) {
e.printStackTrace(); //donde va el stacktrace?
}
}
public String readResponse() { //autogenera como private!, cambio a public!
Log.d("msg" , "entra a buscar");
StringBuilder builder = new StringBuilder();
HttpClient client = new DefaultHttpClient();
//HttpGet httpGet = new HttpGet("http://twitter.com/statuses/user_timeline/vogella.json");
HttpGet httpGet = new HttpGet("http://myswitch.merged.stage.orchard.net.au/LifftService.svc/JSON/CoverageSearchByLatLong/-33.881393,151.214534");
//httpGet.setHeader("Content-Type", "text/plain; charset=utf-8");
//httpGet.setHeader("Content-Type", "json");
try {
HttpResponse response = client.execute(httpGet); //que es?
StatusLine statusLine = response.getStatusLine(); //que es?
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) { //200?
HttpEntity entity = response.getEntity(); //que es?
InputStream content = entity.getContent(); //que es?
BufferedReader reader = new BufferedReader(new InputStreamReader(content)); //que es?
String line;
while ((line = reader.readLine()) != null) {
builder.append(line);
}
} else {
Log.d("msg" , "Failed to download file");
}
} catch (ClientProtocolException e) {
e.printStackTrace();
Log.d("msg", "client protocol exception:"+e);
} catch (IOException e) {
e.printStackTrace();
Log.d("msg", "client protocol exception:"+e);
}
return builder.toString();
}
注意,它取出由JSON數據時的工作原理Twitter的:
//HttpGet httpGet = new HttpGet("http://twitter.com/statuses/user_timeline/vogella.json");
,但顯示爲空白,從我所希望的服務器獲取時:
HttpGet httpGet = new HttpGet("http://myswitch.merged.stage.orchard.net.au/LifftService.svc/JSON/CoverageSearchByLatLong/-33.881393,151.214534");
當它返回空白時,我沒有錯誤消息,
我必須設置指定它的標頭是JSON嗎?怎麼樣?
//httpGet.setHeader("Content-Type", "json");
我會開始通過對URL進行cURL調試來查看Android響應和cURL響應之間的差異。 – curioustechizen 2012-01-10 06:26:59