-2
`package com.tricks.readjsonfromurl;不能從GIven URL訪問JSON不知道爲什麼?
import java.io.IOException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
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.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.os.Bundle;
import android.os.StrictMode;
import android.app.Activity;
import android.widget.ScrollView;
import android.widget.TextView;
public class MainActivity extends Activity
{
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
.detectDiskReads()
.detectDiskWrites()
.detectNetwork() // or .detectAll() for all detectable problems
.penaltyLog()
.build());
TextView showJSON = (TextView) findViewById(R.id.JSONfromURL);
//ScrollView ScrollJSON = (ScrollView) findViewById(R.id.scrollView);
JSONObject json = null;
String str = "";
HttpResponse response;
HttpClient myClient = new DefaultHttpClient();
//This the url from which i am expecting to get JSON Data.
HttpGet myConnection = new HttpGet("http://www.clusterdev.com/flipkart-api-demo/category-example.html");
//Same Code but different URL i've commented below and this URL is //returning Data WTF??
//HttpGet myConnection = new HttpGet("http://api.openweathermap.org/data/2.1/find/station?bbox=12,32,15,37,10&cluster=yes");
try
{
response = myClient.execute(myConnection);
str = EntityUtils.toString(response.getEntity(), "UTF-8");
}
catch (ClientProtocolException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
try
{
//Getting nothing from the URL.
JSONObject jsonObject = new JSONObject(str);
String showJSONIntoTextView = jsonObject.toString();
showJSON.setText(showJSONIntoTextView);
}
catch (JSONException e)
{
e.printStackTrace();
}
}
}`I want to get `JSON` Data from the `URL`, `URL` contains `JSON` data only but giving nothing.
http://www.clusterdev.com/flipkart-api-demo/category-example.html
所有我想要做的是從上面的網址 返回JSON
數據並顯示在一個Android的TextView。
謝謝您提前。
能否請您讓我們知道,正是你在你的代碼已經試過嗎? –
好的,我要粘貼代碼。 –
你的頁面是一個html頁面。它看起來像一個JSON文件,但它不是。 – njzk2