Android網絡開發(fā)中GET與POST請求詳解
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ù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Android編程動態(tài)加載布局實例詳解【附demo源碼】
這篇文章主要介紹了Android編程動態(tài)加載布局,結合實例形式分析了Android動態(tài)加載布局的原理、操作步驟與相關實現技巧,需要的朋友可以參考下2016-10-10Android Studio全局搜索快捷鍵(Ctrl+Shift+F)失效問題及解決
這篇文章主要介紹了Android Studio全局搜索快捷鍵(Ctrl+Shift+F)失效問題及解決方案,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-01-01Android無限循環(huán)RecyclerView的完美實現方案
這篇文章主要介紹了Android無限循環(huán)RecyclerView的完美實現方案,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2019-06-06Android使用CrashHandler來獲取應用的crash信息的方法
本篇文章主要介紹了Android使用CrashHandler來獲取應用的crash信息的方法,具有一定的參考價值,有興趣的可以了解一下2017-09-09