发送get请求
private void requestDataByGet() {
try {
URL url = new URL("http://www.imooc.com/api/teacher?type=2&page=1");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setConnectTimeout(30*1000);
connection.setRequestMethod("GET");
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("Charset", "UTF-8");
connection.setRequestProperty("Accept-Charset", "UTF-8");
connection.connect(); // 发起连接
int responseCode = connection.getResponseCode();
String reponseMessage = connection.getResponseMessage();
if(responseCode == HttpURLConnection.HTTP_OK){
InputStream inputStream = connection.getInputStream();
mResult = streamToString(inputStream);
//跳回主线程
runOnUiThread(new Runnable() {
@Override
public void run() {
mResult = decode(mResult);
mTextView.setText(mResult);
}
});
} else {
// TODO: error fail
Log.e(TAG, "run: error code:" +responseCode +", message:" + reponseMessage);
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
发送post请求:
private void requestDataByPost() {
try {
// ?type=2&page=1
URL url = new URL("http://www.imooc.com/api/teacher");
HttpURLConnection connection = (HttpUR