Android Studio中http請求方式
阿新 • • 發佈:2019-01-28
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import android.widget.ProgressBar;
import com.google.gson.Gson;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.ssl.AllowAllHostnameVerifier;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private ListView listView;
private ProgressBar progressBar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btnClient = (Button) findViewById(R.id.btn_client);
Button btnUrl = (Button) findViewById(R.id.btn_url);
listView = (ListView) findViewById(R.id.lv);
progressBar=(ProgressBar) findViewById(R.id.progressBar);
//初使化為 看不見的狀態
progressBar.setVisibility(View.INVISIBLE);
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"});
}
});
}
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 = 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 =streamToString(inputStream);
}
} catch (Exception ex) {
ex.printStackTrace();
}
} else {
}
return resultStr;
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
Log.d("zzz", s);
//進行解析,並顯示到listView上
// Gson gson=new Gson();
// ResultBean resultBean=gson.fromJson(s,ResultBean.class);
List<News> newsList=new ArrayList<News>();
try {
JSONObject obj=new JSONObject(s);
JSONArray array=obj.optJSONArray("newslist");
for(int i=0;i<array.length();i++){
JSONObject news=array.optJSONObject(i);
News ns=new News();
ns.setCtime(news.optString("ctime"));
ns.setDescription(news.optString("description"));
ns.setPicUrl(news.optString("picUrl"));
ns.setTitle(news.optString("title"));
ns.setUrl(news.optString("url"));
newsList.add(ns);
}
} catch (JSONException e) {
e.printStackTrace();
}
//設定listview的介面卡
MyLvAdapter adapter=new MyLvAdapter(newsList,MainActivity.this);
listView.setAdapter(adapter);
//請求完成時,進度條控制元件為不可見狀態
progressBar.setVisibility(View.INVISIBLE);
//請求完成時,設定listview為可見狀態
listView.setVisibility(View.VISIBLE);
}
@Override
protected void onPreExecute() {
super.onPreExecute();
//設定進度條為顯示的狀態
progressBar.setVisibility(View.VISIBLE);
//設定listview為不可見狀態
listView.setVisibility(View.INVISIBLE);
}
}
/**
* 將流轉換成字串
* @param stream
* @return
*/
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();
}