HttpGet+聚合数据查询空气状况
在别人基础上改的,互相学习吧 原帖网址
http://blog.csdn.net/u012711313/article/details/45666383;
聚合数据首页http://www.juhe.cn/;
可以再里边自己申请ApI和key
package com.example.handlertest02;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.os.Bundle;
import android.os.StrictMode;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
//api接口
private static final String JUHE_URL_ENVIRONMENT_AIR_PM =
"http://web.juhe.cn:8080/environment/air/pm";
//api调用参数key
private static final String JUHE_APPKEY = "804e97c8a5f64968f22352b567aa2222";
EditText et_city;
Button btn_query;
TextView tv_result;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// 强制直接在UI线程中进行网络操作
//这段代码下边有错,右击项目->AndroidTools->clear Link Markets.每次运行都要这样
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
.detectDiskReads().detectDiskWrites().detectNetwork()
.penaltyLog().build());
StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
.detectLeakedSqlLiteObjects().detectLeakedClosableObjects()
.penaltyLog().penaltyDeath().build());
setContentView(R.layout.activity_main);
et_city = (EditText)findViewById(R.id.city);
tv_result = (TextView)findViewById(R.id.result);
btn_query = (Button)findViewById(R.id.query);
btn_query.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
tv_result.setText("");
String city;
city = et_city.getText().toString();
if (city.length() < 1) {
Toast.makeText(MainActivity.this, "请输入城市名",
Toast.LENGTH_LONG).show();
return;
}
ArrayList<NameValuePair> headerList = new ArrayList<NameValuePair>();
headerList.add(new BasicNameValuePair("Content-Type",
"text/html; charset=utf-8"));
String targetUrl = JUHE_URL_ENVIRONMENT_AIR_PM;
ArrayList<NameValuePair> paramList = new ArrayList<NameValuePair>();
//下面的参数要看具体的api参数格式,在此基础上改下就行
paramList.add(new BasicNameValuePair("city", city));
paramList.add(new BasicNameValuePair("key", JUHE_APPKEY));
for (int i = 0; i < paramList.size(); i++) {
NameValuePair nowPair = paramList.get(i);
String value = nowPair.getValue();
try {
value = URLEncoder.encode(value, "UTF-8");
} catch (Exception e) {
}
if (i == 0) {
targetUrl += ("?" + nowPair.getName() + "=" + value);
} else {
targetUrl += ("&" + nowPair.getName() + "=" + value);
}
}
HttpGet httpRequest = new HttpGet(targetUrl);
try {
for (int i = 0; i < headerList.size(); i++) {
httpRequest.addHeader(headerList.get(i).getName(),
headerList.get(i).getValue());
}
HttpClient httpClient = new DefaultHttpClient();
HttpResponse httpResponse = httpClient.execute(httpRequest);
if (httpResponse.getStatusLine().getStatusCode() == 200) {
String strResult = EntityUtils.toString(httpResponse.getEntity());
try {
//jason格式解析
JSONObject toot=new JSONObject(strResult);
JSONArray arry=toot.getJSONArray("result");
JSONObject yth=arry.getJSONObject(0);
String mycity=yth.getString("city");
String pm=yth.getString("PM2.5");
tv_result.setText("城市 :"+mycity+"\n"+"PM2.5 :"+pm);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else {
Toast.makeText(MainActivity.this, "查询失败",
Toast.LENGTH_LONG).show();
tv_result.setText("");
}
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
Xml文件
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
>
<TextView
android:id="@+id/tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world" />
<Button
android:id="@+id/btn_start"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="开始" />
<Button
android:id="@+id/btn_stop"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="停止" />
<ProgressBar
android:id="@+id/progressBar1"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:max="100"/>
</LinearLayout>
注意在AndroidManifest.xml中添加网络访问权限