public String getBrotherHood() throws Exception{
client = new DefaultHttpClient();
get = new HttpGet(uri);
res = client.execute(get);
sl = res.getStatusLine();
sCode = sl.getStatusCode();
if(sCode==200)
{
try{
reader = new BufferedReader(new InputStreamReader(res.getEntity().getContent()));
readBuffer = new StringBuffer();
while((nl = reader.readLine())!=null){
readBuffer.append(nl);
}
reader.close();
}finally{
if(reader !=null)
{
try{
reader.close();
}catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
}
}
return readBuffer.toString();
}
}
我有这段代码,这是正确的编写方式,还是我需要遵循任何编码模式或标准?
请给我一些建议,因为我不是 Android Coding。
更新:
public class JSONData {
public ArrayList<String> getBrotherHoodJSON() throws JSONException,IOException,Exception{
ArrayList<String> item = new ArrayList<String>();
JSONArray jA = new JSONArray(getBrotherHood());
for(int i=0; i<jA.length(); i++)
{
JSONObject jO = jA.getJSONObject(i);
String n = jO.getString("name");
item.add(n);
Log.i("JsonData:",jO.getString("name"));
}
return item;
}
public String getBrotherHood() throws Exception{
BufferedReader in = null;
String data= null;
HttpClient client = new DefaultHttpClient();
URI uri = new URI("http://fahidmohammad.in/demo/Android/api.php?user=fah");
HttpGet get = new HttpGet();
get.setURI(uri);
HttpResponse res = client.execute(get);
StatusLine sl = res.getStatusLine();
int sCode = sl.getStatusCode();
if(sCode==200)
{
try{
in = new BufferedReader(new InputStreamReader(res.getEntity().getContent()));
StringBuffer sb = new StringBuffer();
String nl;
while((nl = in.readLine())!=null){
sb.append(nl);
}
in.close();
data = sb.toString();
Log.i("Raw Data:",data);
return data;
}finally{
if(in !=null)
{
try{
in.close();
return data;
}catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
}
}
return data;
}
这是相同代码的更新版本。处理了所有提到的问题。
而且它的工作就像一个魅力,但不知道它的稳定性。