Button btnClient = (Button) findViewById(R.id.btn_client);
Button btnUrl = (Button) findViewById(R.id.btn_url);
ListView listView = (ListView) findViewById(R.id.lv);
btnClient.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//执行异步任务
MyTask myTask = new MyTask();
myTask.execute(new String[]{"https://api.tianapi.com/wxnew/?key=8d6e3228d25298f13af4fc40ce6c9679&num=10", "1"});
}
});
btnUrl.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//执行异步任务
MyTask myTask = new MyTask();
myTask.execute(new String[]{"https://api.tianapi.com/wxnew/?key=8d6e3228d25298f13af4fc40ce6c9679&num=10", "2"});
}
});
streamToString方法:
public String streamToString(InputStream stream) {
StringBuilder builder = new StringBuilder();
try {
BufferedReader br = new BufferedReader(new InputStreamReader(stream, "utf-8"));
String con;
while ((con = br.readLine()) != null) {
builder.append(con);
}
} catch (Exception ex) {
ex.printStackTrace();
}
return builder.toString();
}
class MyTask extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... params) {
String resultStr = "";
//得到请求的类型
String type = params[1];
if ("1".equals(type)) {//如果是"1" 执行 HttpGet请求
//因为请求的是https协议的网址,eclipse下使用HttpGet请求会报错,需要添加以下这行代码
SSLSocketFactory.getSocketFactory().setHostnameVerifier(new AllowAllHostnameVerifier());
//1.创建一个HttpClient对象
HttpClient hc = new DefaultHttpClient();
//2.创建httpGet对象
HttpGet hg = new HttpGet(params[0]);
try {
//3.执行请求
HttpResponse response = hc.execute(hg);
//4.判断结果码
int code = response.getStatusLine().getStatusCode();
if (code == 200) {
//5.得到请求的结果
HttpEntity result = response.getEntity();
resultStr = "client请求:" + EntityUtils.toString(result);
}
} catch (IOException e) {
e.printStackTrace();
}
} else if ("2".equals(type)) {//如果是2执行 HttpUrlConnection请求
try {
//1.创建Url对象
URL url = new URL(params[0]);
//2.打开连接
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
//3.设置
connection.setRequestMethod("GET");
connection.setConnectTimeout(5000);
connection.setReadTimeout(5000);
//4.得到响应码,进行判断
int code = connection.getResponseCode();
if (code == 200) {
//5.得到结果
InputStream inputStream = connection.getInputStream();
resultStr = "url请求:" + streamToString(inputStream);
}
} catch (Exception ex) {
ex.printStackTrace();
}
} else {
}
return resultStr;
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
Log.d("zzz", s);
}
@Override
protected void onPreExecute() {
super.onPreExecute();
}
}