Android Studio——Android网络请求之GET与POST

1.URI与URL

  • URI(Uniform Resource Identifier,统一资源标志符),表示web上的每一种可用资源,具体的东西例如HTML文档,图像、视频、程序等。
  • URL(Uniform Resource Locator,统一资源定位器),也就是网络地址。
  • URL是URI的一种。
  • URI是对网络资源更宽泛的一种标识。
  • URL通常指的是网络连接,更多以http://www开头。

2.申请一个天气的免费API

  • 网址:https://www.yiketianqi.com/index/doc,登陆后会自动生成属于自己的appid和appsecret
    在这里插入图片描述

2.GET请求

  • 主要目的:从服务端获取符合条件的数据。
  • 会向服务端发送少量数据,携带的参数会拼接在URL后面,参数是少量而有限的
  • GET请求的URL举例:https://www.tianqiapi.com/free/day?cityid=10010&cityname=北京&data=20220728
  • 协议(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来发送消息
				Message message = new Message();
				message.what = 0;//用于区分是谁发的消息
    			message.obj = stringFormNet;
    			mHandler.sendMessage(meaasge);
    			
    			}
    		}).start();
    		Toast.makeText(MainActivity.this,"开启子线程请求网络!",Toast.LENGTH_SHORT).show();
    		}
    		
    private String getStringFormNet(){
		//从网络上获取字符串
		return NetUtil.getWeatherofCity("深圳");
	}
}

运行结果:
在这里插入图片描述

3.POST请求

  • 主要目的:向服务端提交数据
  • 也会接收少量服务端的响应数据,携带的参数会单独放到map中,参数是大量的。
  • POST请求的URL举例: https://www.tianqiapi.com/free/day+Map<String,String><city_id,1010><city_name,北京><date,20220728>
  • 0
    点赞
  • 28
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值