我有jsonparser类逐行读取页面并在我的jsonparser类中将其转换为json.But,当我尝试逐行读取页面时,readLine()返回null。
这是我的JsonParser.java
final String TAG = "JsonParser.java";
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
public JSONObject getJSONFromUrl(String url) {
// make HTTP request
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
if(line.contains(";"))
{
line=line.replace(";", "");
}
if(line.contains("info = "))
{
line.replace("info = ","");
}
sb.append(line + "\n");
}
is.close();
Log.e(TAG, "Control5");
json=sb.toString();
}catch(IOException e)
{
Log.e(TAG, "IOException occurred!!");
}
catch (Exception e) {
Log.e(TAG, "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
Log.e(TAG,json);
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e(TAG, "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
我在Asynctask的MainActivity.java中使用这个类。
String videoid="mAQln4dgR24";
long currenttime=System.currentTimeMillis() / 1000;
yourJsonStringUrl="http://www.youtube-mp3.org/a/itemInfo/?video_id="+videoid+"&ac=www&t=grp&r="+currenttime;
/*
//if you want to see the page use browserintent.
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(yourJsonStringUrl));
startActivity(browserIntent);
*/
JsonParser jParser = new JsonParser();
// get json string from url
JSONObject json = jParser.getJSONFromUrl(yourJsonStringUrl);
链接" jsonstringurl"将在程序运行时生成。 它打破了很少的时间。如果你想看到页面使用浏览器意图。