从android中的asynctask获取字符串

时间:2015-01-29 08:01:27

标签: android string android-asynctask

我已经搜索了几个关于此的标题,但我无法以正确的方式完成我想做的事情。我想用GET url连接服务器,并且必须将return xml文件读入一个我可以在不同活动中使用的字符串。当我调试它时,我的代码工作正常,但是我无法从中获得正确的字符串返回。

    protected JSONArray doInBackground(String... params) {
    URL url;
    HttpURLConnection urlConnection = null;
    JSONArray response = new JSONArray();

    try {
        url = new URL(params[0]);
        urlConnection = (HttpURLConnection) url.openConnection();
        int responseCode = urlConnection.getResponseCode();

        if(responseCode == HttpStatus.SC_OK){
            String responseString = readStream(urlConnection.getInputStream());
            Log.v("CatalogClient", responseString);
            response = new JSONArray(responseString);
        }else{
            Log.v("CatalogClient", "Response code:"+ responseCode);
        }

    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if(urlConnection != null)
            urlConnection.disconnect();
    }

    return response;
}

private String readStream(InputStream in) {
    BufferedReader reader = null;
    StringBuffer response = new StringBuffer();
    try {
        reader = new BufferedReader(new InputStreamReader(in));
        String line = "";
        while ((line = reader.readLine()) != null) {
            response.append(line);
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (reader != null) {
            try {
                reader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    return response.toString();
}

1 个答案:

答案 0 :(得分:-1)

试试这个

public class MainActivity extends ActionBarActivity {

Helper parser = new Helper();
Document doc;
NodeList nl;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);


    callUrl();

}

private void callUrl() {

    new NetworkRequest(new CallbackInterface() {

        @Override
        public void onRequestSuccess(String result) {
            doc = parser.getDocumentElement(result);
            nl = doc.getElementsByTagName("item");

            for (int i = 0; i < nl.getLength(); i++) {


                String id = parser.getValue(element, "id");
                String name = parser.getValue(element, "name");
                String cost = parser.getValue(element, "cost");
                String description = parser.getValue(element, "description");

                Log.i("Values", id + name + cost + description);
            }

        }
    }, "").execute();
}
}

创建Helper类来解析数据

public class Helper {

public Document getDocumentElement(String xml) {

    Document doc = null;

    try {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        InputSource is = new InputSource();
        is.setCharacterStream(new StringReader(xml));
        doc = db.parse(is);
    } catch (SAXException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (ParserConfigurationException e) {
        e.printStackTrace();
    }

    return doc;

}

public String getValue(Element item, String str) {
    NodeList n = item.getElementsByTagName(str);
    return this.getElementValue(n.item(0));
}

public final String getElementValue(Node elem) {
    Node child;
    if (elem != null) {
        if (elem.hasChildNodes()) {
            for (child = elem.getFirstChild(); child != null; child = child
                    .getNextSibling()) {
                if (child.getNodeType() == Node.TEXT_NODE) {
                    return child.getNodeValue();
                }
            }
        }
    }
    return "";
}
}

创建NetworkRequest类

public class NetworkRequest extends AsyncTask<Void, Void, String> {

private String url = "http://api.androidhive.info/pizza/?format=xml";
private CallbackInterface callBack;
private String result;

public interface CallbackInterface {
    public void onRequestSuccess(String result);
}

public NetworkRequest(CallbackInterface callBack, String url) {
    this.url += url;
    this.callBack = callBack;
}

@Override
protected String doInBackground(Void... params) {

    try {
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);
        HttpResponse httpResponse = httpClient.execute(httpPost);
        HttpEntity httpEntity = httpResponse.getEntity();
        result = EntityUtils.toString(httpEntity);
        return result;

    } catch (ClientProtocolException e) {
        e.printStackTrace();
        return null;
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
}

@Override
protected void onPostExecute(String result) {
    super.onPostExecute(result);
    callBack.onRequestSuccess(result);
}
}