我正在尝试解析一些我收到的JSON数据作为来自网址的回复。
我得到了完整的响应,但是当我使用BufferedReader读取响应时,我只得到部分数据,我无法读取响应的全部内容。
我也尝试将内容写入.txt文件并再次从该文件中读取内容,但仍然只读取部分数据,而不是整个文件内容。
任何人都有解决方案......
这是我的代码,
package com.example.asynctest;
/*I have excluded the imports*/
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new MyAsyncTask().execute();
}
class MyAsyncTask extends AsyncTask<String, String, Void>{
public String readBugzilla() {
StringBuilder builder = new StringBuilder();
HttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet("https://bugzilla.mozilla.org/rest/bug?assigned_to=lhenry@mozilla.com");
try {
HttpResponse response = client.execute(httpGet);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) {
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
/*I tried to Read the InputStream here, but it was incomplete, so I decided to write the contents of the inputstream into a text file, and then read the contents later on*/
String fileName = "category.txt";
File destinationFile = new File(getExternalFilesDir(null), fileName);
BufferedOutputStream buffer = new BufferedOutputStream(new FileOutputStream(destinationFile));
byte byt[] = new byte[100000];
int i;
for (long l = 0L; (i = content.read(byt)) != -1; l += i ) {
buffer.write(byt, 0, i);
}
buffer.close();
//Read text from file
File file = new File(getExternalFilesDir(null),"category.txt");
StringBuilder text = new StringBuilder();
try {
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
text.append(line);
Log.d("Law", "line is "+line);
}
br.close();
Log.d("Law","Text is "+text.toString());
}
catch (IOException e) {
//You'll need to add proper error handling here
Log.d("Law IO", e.toString());
}
} else {
Log.e("Law", "Failed to download file");
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return builder.toString();
}
@Override
protected Void doInBackground(String... arg0) {
// TODO Auto-generated method stub
String response = readBugzilla();
Log.d("Law", "Response "+response);
return null;
}
我真的尽我所能,但无法找到解决这个问题的方法,也许有人用更好的技术来解决这个问题。