初学_Android4高级编程-7 异步http框架得到有道翻译的XML与json资源并解析出需要的数据&使用DownloadManager
※使用URLConnection连接Internet资源
try {
URL url = new URL("www.baidu.com");
URLConnection connection = url.openConnection();
HttpURLConnection httpURLConnection = (HttpURLConnection) connection;
int responseCode = httpURLConnection.getResponseCode();
if(responseCode == 200){
InputStream inputStream = httpURLConnection.getInputStream();
}
} catch (IOException e) {
e.printStackTrace();
}
※使用AsyncHttpClient连接有道翻译,获取xml,json格式的资源并解析。
初始化组件
textView = (TextView) findViewById(R.id.id_textview);
textView2 = (TextView) findViewById(R.id.id_textview2);
editText = (EditText) findViewById(R.id.id_edit_text);
Button button = (Button) findViewById(R.id.id_button_json);
Button button1 = (Button) findViewById(R.id.id_button_xml);
button.setOnClickListener(this);
button1.setOnClickListener(this);
点击事件
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.id_button_xml:
connect("xml");
break;
case R.id.id_button_json:
connect("json");
break;
}
}
//连接有道翻译并获取资源
public void connect(final String doctype){
final AsyncHttpClient httpClient = new AsyncHttpClient();
RequestParams params = new RequestParams();
params.put("keyfrom", "sdasfafas");
params.put("key", "66594842");
params.put("type", "data");
params.put("doctype", doctype);
params.put("version", "1.1");
params.put("q", editText.getText());
httpClient.get("http://fanyi.youdao.com/openapi.do", params, new AsyncHttpResponseHandler() {
@Override
public void onSuccess(int i, Header[] headers, byte[] bytes) {
if(doctype.equals("xml")){
try {
textView2.setText("xml格式\n" + parsingXml(new ByteArrayInputStream(bytes)));
} catch (Exception e) {
e.printStackTrace();
}
} else {
textView.setText("json格式\n" + parsingJson(bytes));
}
}
@Override
public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) {
textView.setText("连接失败");
textView2.setText("");
}
});
}
//解析Json
public String parsingJson(byte[] bytes) {
StringBuilder ans = new StringBuilder();
try {
JSONObject jsonObject = new JSONObject(new String(bytes, "UTF-8"));
JSONArray jsonArray = jsonObject.getJSONObject("basic").getJSONArray("explains");
for (int j = 0; j < jsonArray.length(); j++) {
if (j != 0) {
ans.append("\n");
}
ans.append(jsonArray.getString(j));
}
} catch (JSONException | UnsupportedEncodingException e) {
e.printStackTrace();
}
return ans.toString();
}
//解析Xml
public String parsingXml(InputStream inputStream) throws Exception {
StringBuffer ans = new StringBuffer();
XmlPullParser parser = Xml.newPullParser();
parser.setInput(inputStream, "UTF-8");
int eventType = parser.getEventType();
parser.next();
while (eventType != XmlPullParser.END_DOCUMENT) {
if (eventType == XmlPullParser.START_TAG && parser.getName().equals("explains")) {
parser.nextTag();
while (eventType == XmlPullParser.START_TAG && parser.getName().equals("ex")) {
parser.next();
ans.append(parser.getText()).append("\n");
parser.nextTag();
eventType = parser.nextTag();
}
}
eventType = parser.next();
}
return ans.toString();
}
※使用DownloadManager下载文件
下载文件并动态注册一个广播接收器监听下载完成
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = (Button) findViewById(R.id.button);
final TextView textView = (TextView) findViewById(R.id.text_view);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
DownloadManager downloadManager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
Uri uri = Uri.parse("http://www.baidu.com/link?url=tFfogxNoCPbAgWS5g2dsoOmx0IO-oNS8N4f2UFcLkuSopfdQvD81Nc2sBD8aMxjdsU8wos9J4DIaJV9DJY0ARSj_0qR_RUVan_aUkHNWKGvELk0MPT5Vst5fQ4HsipCd");
DownloadManager.Request request = new DownloadManager.Request(uri);
request.setDescription("百度手机助手");
//下载完成后也会继续在标题栏显示Notification
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
long reference = downloadManager.enqueue(request);
}
});
thread.start();
}
});
IntentFilter filter = new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE);
BroadcastReceiver receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
long refrence = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID,-1);
textView.setText("Complete , "+refrence);
}
};
registerReceiver(receiver,filter);
}
浙公网安备 33010602011771号