欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Android網絡開發(fā)中GET與POST請求詳解

 更新時間:2022年12月13日 16:19:45   作者:小徐加油  
這篇文章主要介紹了android實現網絡請求的get和post請求的簡單封裝與使用,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧<BR>

1.URI與URL

URI(Uniform Resource Identifier,統(tǒng)一資源標志符),表示web上的每一種可用資源,具體的東西例如HTML文檔,圖像、視頻、程序等。

URL(Uniform Resource Locator,統(tǒng)一資源定 位 器),也就是網絡地址。

URL是URI的一種。

URI是對網絡資源更寬泛的一種標識。

URL通常指的是網絡連接,更多以http://www開頭。

2.申請一個天氣的免費API

網址:https://www.yiketianqi.com/index/doc,登陸后會自動生成屬于自己的appid和appsecret

3.GET請求

主要目的:從服務端獲取符合條件的數據。

會向服務端發(fā)送少量數據,攜帶的參數會拼接在URL后面,參數是少量而有限的

GET請求的URL舉例:

https://www.tianqiapi.com/free/day?cityid=10010&cityname=北京&data=20220728

協(xié)議(https://)域名及端口(www.tianqiapi.com:80) 路徑(/free/day)條件(cityid=10010&cityname=北京&data=20220728)

NetUtil程序如下:

public class NetUtil{
	public static String BASE_URL="https://v0.yiketianqi.com/free/day";
	public static String APP_ID="14846972";
	public static String APP_SECRET="Guya4Gz2";
	public static String doGet(String url){ 
		BufferedReader reader = null;
		String bookHSONString = null;
		try{
			//1.HttpURLConnection建立連接
			HttpURLConnection httpURLConnection = null;
			URL requestUrl = new URL(url);
			httpURLConnection = (HttpURLConnection)requestUrl.openconnection();//打開連接
			httpURLConnection.setRequestMethod("GET");//兩種方法GET/POST
			httpURLConnection.setConnectionTimeout(5000);//設置超時連接時間
			httpURLConnection.connect();
			//2.InputStream獲取二進制流
			InputStream inputstream = httpURLConnection.getInputStream();
			//3.InputStreamReader將二進制流進行包裝成BufferedReader
			reader = new BufferedReader(new InputStreamReader(inputStream));
			//4.從BufferedReader中讀取String字符串,用StringBulider接收
			StringBulider bulider = new StringBulider();
			String line;
			while((line=reader.readLine())!=null){
				bulider.append(line);
				bulider.append("\n");
				}
			if(bulider.length()==0)
			{
				return null;
			}
			//5.StringBulider將字符串進行拼接
			bookJSONString = bulider.toString();
			}catch(MalformedURLException e){
			e.printStackTrace();
			}finally {
            // 關閉連接
            if (urlConnection != null) {
                urlConnection.disconnect();
            }
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
		return bookJSONString;
		}
	public static String getWeatherOfCity(String city){
		//拼接處get請求的url
		String weatherUrl = BASE_URL+"?"+"appid="+APP_ID+"&"+"appsecret="+APP_SECRET+"&"+"city="+city;
		//打印上面的url
		Log.d("fan","-----weatherUrl----"+weatherUrl);
		//調用上文所寫的doGet方法,傳參
		String weatherResult = doGet(weatherUrl);
		return decodeUnicode(weatherResult);
	}
	//解碼Unicode,將其轉化為我們認識的漢字
	public static String decodeUnicode(String unicodeStr) {
        if (unicodeStr == null) {
            return null;
        }
        StringBuffer retBuf = new StringBuffer();
        int maxLoop = unicodeStr.length();
        for (int i = 0; i < maxLoop; i++) {
            if (unicodeStr.charAt(i) == '\\') {
                if ((i < maxLoop - 5) && ((unicodeStr.charAt(i + 1) == 'u') || (unicodeStr.charAt(i + 1) == 'U')))
                    try {
                        retBuf.append((char) Integer.parseInt(unicodeStr.substring(i + 2, i + 6), 16));
                        i += 5;
                    } catch (NumberFormatException localNumberFormatException) {
                        retBuf.append(unicodeStr.charAt(i));
                    }
                else
                    retBuf.append(unicodeStr.charAt(i));
            } else {
                retBuf.append(unicodeStr.charAt(i));
            }
        }
        return retBuf.toString();
    }
}

MainActivity.java程序如下:

public class MainActivity extends AppCompatActivity{
	private TextView tvContent;
	//此處寫一個handler程序
	private Handler mHandler = new Handler(Looper.myLooper()){
		@Override
		public void handleMessage(@NonNull Message msg){
		super.handlerMessage(msg);
		if(msg.what==0){
			String strData = (String)msg.obj;
			tvContent.setText(strData);
			Toast.makeText(MainActivity.this,"主線程收到網絡消息啦!",Toast.LENGTH_SHORT).show();
			}
		}
	};
	@Override
	protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tvContent = findViewById(R.id.tv_content);
    }
    public void start(View view){
    	//做一個耗時任務
    	new Thread(new Runnable(){
    		@Override
    		public void run(){
    			String stringFormNet = getStringFormNet();
    			//使用handler來發(fā)送消息
				Message message = new Message();
				message.what = 0;//用于區(qū)分是誰發(fā)的消息
    			message.obj = stringFormNet;
    			mHandler.sendMessage(meaasge);
    			}
    		}).start();
    		Toast.makeText(MainActivity.this,"開啟子線程請求網絡!",Toast.LENGTH_SHORT).show();
    		}
    private String getStringFormNet(){
		//從網絡上獲取字符串
		return NetUtil.getWeatherofCity("深圳");
	}
}

運行結果:

4.POST請求

主要目的:向服務端提交數據。

也會接收少量服務端的響應數據,攜帶的參數會單獨放到map中,參數是大量的。

POST請求的URL舉例:

https://www.tianqiapi.com/free/day+Map<String,String><city_id,1010><city_name,北京><date,20220728>

到此這篇關于Android網絡開發(fā)中GET與POST請求詳解的文章就介紹到這了,更多相關Android GET與POST內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

相關文章

最新評論