【发布时间】:2018-04-23 08:34:29
【问题描述】:
我正在处理 Url 解析,通过使用 HttpURLConnection 作为 {"USD_PKR":115.599998} 得到响应。从我的回复中,我想通过解析上面提取的数据来获得 115.599998 的值。我的代码如下,请指导我获取我提取的String 值。
private class MakeNetworkCall extends AsyncTask<String, Void, String> {
@Override
protected void onPreExecute() {
super.onPreExecute();
// DisplayMessage("Please Wait ...");
}
@Override
protected String doInBackground(String... arg) {
InputStream is = null;
String URL = arg[0];
Log.d("", "URL: " + URL);
String res = "";
is = ByGetMethod(URL);
if (is != null) {
res = ConvertStreamToString(is);
} else {
res = "Something went wrong";
}
return res;
}
protected void onPostExecute(String result) {
super.onPostExecute(result);
// DisplayMessage(result);
convert_result.setVisibility(View.VISIBLE);
convert_result.setText(result);
// Here I am getting a response as {"USD_PKR":115.599998}, I want to extract the value as 115.599998
Log.d("Result: ", "Result: " + result);
}
}
String ConvertStreamToString(InputStream stream) {
InputStreamReader isr = new InputStreamReader(stream);
BufferedReader reader = new BufferedReader(isr);
StringBuilder response = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
response.append(line);
}
} catch (IOException e) {
Log.e("Error", "Error in ConvertStreamToString", e);
} catch (Exception e) {
Log.e("Error", "Error in ConvertStreamToString", e);
} finally {
try {
stream.close();
} catch (IOException e) {
Log.e("Error", "Error in ConvertStreamToString", e);
} catch (Exception e) {
Log.e("Error", "Error in ConvertStreamToString", e);
}
}
return response.toString();
}
InputStream ByGetMethod(String ServerURL) {
InputStream DataInputStream = null;
try {
URL url = new URL(ServerURL);
HttpURLConnection cc = (HttpURLConnection)
url.openConnection();
//set timeout for reading InputStream
cc.setReadTimeout(5000);
// set timeout for connection
cc.setConnectTimeout(5000);
//set HTTP method to GET
cc.setRequestMethod("GET");
//set it to true as we are connecting for input
cc.setDoInput(true);
//reading HTTP response code
int response = cc.getResponseCode();
//if response code is 200 / OK then read Inputstream
if (response == HttpURLConnection.HTTP_OK) {
DataInputStream = cc.getInputStream();
}
} catch (Exception e) {
Log.e("Error Get Data", "Error in GetData", e);
}
return DataInputStream;
}
【问题讨论】:
标签: android parsing httpconnection