對自己的Android學習做個總結,方便以後查看。
一、在Android用Get方式發送http請求,使用的是Java標准類,也比較簡單。
主要分以下幾步:
1.構造URL
URL url = new URL(String path);
2.設置連接
httpURLConnection = (HttpURLConnection) url.openConnection();
//超時時間
httpURLConnection.setConnectTimeout(3000);
//表示設置本次http請求使用GET方式
httpURLConnection.setRequestMethod("GET");
int responsecode = httpURLConnection.getResponseCode();//返回至為響應編號,如:HTTP_OK表示連接成功。
3.獲取返回數據
if(responsecode == HttpURLConnection.HTTP_OK){
inputStream = httpURLConnection.getInputStream();
} //得到inputStream 就好辦啦。
new InputStreamReader(inputStream,"utf-8")
4.關閉連接
void disconnect()
二、下面通過一個簡單的Demo實現get方式的請求:
package com.http.get;
import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class HttpUtils {
private static String URL_PATH="http://www.baidu.com";
private static HttpURLConnection httpURLConnection = null;
public HttpUtils(){
}
public static void shuchu(){
InputStream inputStream = getInputStream();
String result;
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream,"utf-8"));
result = "";
String line = "";
try {
while((line = reader.readLine())!= null){
result = result+ line;
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(result);
httpURLConnection.disconnect();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* 獲取服務端的數據,以InputStream返回
* @return
*/
public static InputStream getInputStream(){
InputStream inputStream = null;
try {
URL url = new URL(URL_PATH);
if(url != null){
try {
httpURLConnection = (HttpURLConnection) url.openConnection();
//超時時間
httpURLConnection.setConnectTimeout(3000);
//表示設置本次http請求使用GET方式
httpURLConnection.setRequestMethod("GET");
int responsecode = httpURLConnection.getResponseCode();
if(responsecode == HttpURLConnection.HTTP_OK){
inputStream = httpURLConnection.getInputStream();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return inputStream;
}
public static void main(String[] args){
//保存文件到本地
//saveImageToDisk();
shuchu();
}
}
//因為get方式是這ava標准類,直接寫的java程序,不過都一樣,android中也是一樣的。。
簡單的訪問了百度,返回的就是百度搜索首頁的源代碼:圖片一直上傳不了。。。就不截圖啦。
正確返回的就是你在網頁單擊右鍵有個查看源代碼,返回的就是它,輸出的也是它,自己可以去對比下一樣不,是一樣的。
Android中POST方式發送HTTP請求 http://www.linuxidc.com/Linux/2015-08/121969.htm
更多Android相關信息見Android 專題頁面 http://www.linuxidc.com/topicnews.aspx?tid=11