Android Studio App开发之网络通信中使用GET方式调用HTTP接口的讲解及实战(附源码 超详细必看)

简介: Android Studio App开发之网络通信中使用GET方式调用HTTP接口的讲解及实战(附源码 超详细必看)

运行有问题或需要源码请点赞关注收藏后评论区留言~~~

一、GET方式调用HTTP接口

Android开发采用Java作为编程语言,也就沿用了Java的HTTP连接工具HttpURLConnection,不管是访问HTTP接口还是上传或下载文件都是用它来实现。它有几个关键点

1:HttpURLConnection默认采取国际通行的UTF-8编码,中文用GBK编码

2:多数时候服务器返回的报文采用明文传输,但有时为了提高传输效率,服务器会先压缩应答报文,再把压缩后的数据送给调用方,这样耗费空间小,降低流量占用

3:小心返回报文超长的情况

访问HTTP接口要求APP事先申请网络权限,也就是在AndroidManifest.xml内部添加以下的网络权限配置

<uses-permission android:name="android.permission.INTERNET">
</uses-permission>

同样开启手机的定位权限功能 代码如下

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION">
    </uses-permission>
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION">
    </uses-permission>

定位工具Location包含了丰富的位置信息 部分方法如下

1:getProvider 获取定位类型 主要由网络定位和GPS定位

2:getTime 获取定位时间

3:getLongitude 获取经度

4:getLatitude 获取纬度

5:getAltitude 获取高度

6:getAccuracy 获取定位精度

如果想把经纬度换算为详细地址的文字描述,就要调用地图服务商的地址查询接口,本次案例选用天地图的查询服务  效果如下

模拟机上定位不了 建议连接真机测试

代码如下

Java类

package com.example.chapter14;
import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import com.example.chapter14.task.GetAddressTask;
import com.example.chapter14.task.GetAddressTask.OnAddressListener;
import com.example.chapter14.util.DateUtil;
import com.example.chapter14.util.SwitchUtil;
@SuppressLint("DefaultLocale")
public class HttpGetActivity extends AppCompatActivity implements OnAddressListener {
    private final static String TAG = "HttpGetActivity";
    private TextView tv_location;
    private Location mLocation; // 定位信息
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_http_request);
        tv_location = findViewById(R.id.tv_location);
        // 检查定位功能是否打开,若未打开则跳到系统的定位功能设置页面
        SwitchUtil.checkGpsIsOpen(this, "需要打开定位功能才能查看定位结果信息");
    }
    @Override
    protected void onResume() {
        super.onResume();
        // 检查当前设备是否已经开启了定位功能
        if (ActivityCompat.checkSelfPermission(this,
                Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            Toast.makeText(this, "请授予定位权限并开启定位功能", Toast.LENGTH_SHORT).show();
            return;
        }
        // 从系统服务中获取定位管理器
        LocationManager mgr = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        // 获取最后一次成功定位的位置信息(network表示网络定位方式)
        Location location = mgr.getLastKnownLocation("network");
        getLocationText(location); // 获取定位结果文本
        // 获取最后一次成功定位的位置信息(gps表示卫星定位方式)
        location = mgr.getLastKnownLocation("gps");
        getLocationText(location); // 获取定位结果文本
    }
    // 获取定位结果文本
    private void getLocationText(Location location) {
        if (location != null) {
            mLocation = location;
            refreshLocationInfo(""); // 刷新定位信息
            GetAddressTask task = new GetAddressTask(); // 创建一个详细地址查询的异步任务
            task.setOnAddressListener(this); // 设置详细地址查询的监听器
            task.execute(location); // 把详细地址查询任务加入到处理队列
        }
    }
    // 在找到详细地址后触发
    @Override
    public void onFindAddress(String address) {
        refreshLocationInfo(address); // 刷新定位信息
    }
    // 刷新定位信息
    private void refreshLocationInfo(String address) {
        String desc = String.format("定位类型=%s\n定位对象信息如下: " +
                        "\n\t其中时间:%s" + "\n\t其中经度:%f,纬度:%f" +
                        "\n\t其中高度:%d米,精度:%d米" + "\n\t其中地址:%s",
                mLocation.getProvider(), DateUtil.formatDate(mLocation.getTime()),
                mLocation.getLongitude(), mLocation.getLatitude(),
                Math.round(mLocation.getAltitude()), Math.round(mLocation.getAccuracy()), address);
        tv_location.setText(desc);
    }
}

任务类

package com.example.chapter14.task;
import android.location.Location;
import android.os.AsyncTask;
import android.text.TextUtils;
import android.util.Log;
import com.example.chapter14.constant.UrlConstant;
import com.example.chapter14.util.HttpUtil;
import org.json.JSONException;
import org.json.JSONObject;
// 根据经纬度获取详细地址的异步任务
public class GetAddressTask extends AsyncTask<Location, Void, String> {
    private final static String TAG = "GetAddressTask";
//    public GetAddressTask() {
//        super();
//    }
    // 线程正在后台处理
    protected String doInBackground(Location... params) {
        Location location = params[0];
        // 把经度和纬度代入到URL地址。天地图的地址查询url在UrlConstant.java中定义
        String url = String.format(UrlConstant.GET_ADDRESS_URL,
                location.getLongitude(), location.getLatitude());
        Log.d(TAG, "url = " + url);
        String resp = HttpUtil.get(url, null); // 发送HTTP请求信息,并获得HTTP应答内容
        Log.d(TAG, "resp = " + resp);
        String address = "未知";
        // 下面从JSON串中解析formatted_address字段获得详细地址描述
        if (!TextUtils.isEmpty(resp)) {
            try {
                JSONObject obj = new JSONObject(resp);
                JSONObject result = obj.getJSONObject("result");
                address = result.getString("formatted_address");
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        Log.d(TAG, "address = " + address);
        return address; // 返回HTTP应答内容中的详细地址
    }
    // 线程已经完成处理
    protected void onPostExecute(String address) {
        mListener.onFindAddress(address); // HTTP调用完毕,触发监听器的找到地址事件
    }
    private OnAddressListener mListener; // 声明一个查询详细地址的监听器对象
    // 设置查询详细地址的监听器
    public void setOnAddressListener(OnAddressListener listener) {
        mListener = listener;
    }
    // 定义一个查询详细地址的监听器接口
    public interface OnAddressListener {
        void onFindAddress(String address);
    }
}

日期类

package com.example.chapter14.util;
import android.annotation.SuppressLint;
import android.text.TextUtils;
import java.text.SimpleDateFormat;
import java.util.Date;
@SuppressLint("SimpleDateFormat")
public class DateUtil {
    // 获取当前的日期时间
    public static String getNowDateTime() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        return sdf.format(new Date());
    }
    // 获取当前的时间
    public static String getNowTime() {
        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
        return sdf.format(new Date());
    }
    // 获取当前的时间(精确到毫秒)
    public static String getNowTimeDetail() {
        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss.SSS");
        return sdf.format(new Date());
    }
    // 获取指定格式的日期时间
    public static String getNowDateTime(String formatStr) {
        String format = formatStr;
        if (TextUtils.isEmpty(format)) {
            format = "yyyyMMddHHmmss";
        }
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        return sdf.format(new Date());
    }
    public static String formatDate(long time) {
        Date date = new Date(time);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return sdf.format(date);
    }
    // 重新格式化日期字符串
    public static String convertDateString(String strTime) {
        String newTime = strTime;
        try {
            SimpleDateFormat oldFormat = new SimpleDateFormat("yyyyMMddHHmmss");
            Date date = oldFormat.parse(strTime);
            SimpleDateFormat newFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            newTime = newFormat.format(date);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return newTime;
    }
}

XML文件

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="5dp" >
    <TextView
        android:id="@+id/tv_location"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="暂未获取到定位对象"
        android:textColor="@color/black"
        android:textSize="17sp" />
</LinearLayout>

创作不易 觉得有帮助请点赞 关注收藏~~~

相关文章
|
开发工具 Android开发 iOS开发
如何在Android Studio中配置Flutter环境?
如何在Android Studio中配置Flutter环境?
2964 160
|
Android开发 数据安全/隐私保护 开发者
Android自定义view之模仿登录界面文本输入框(华为云APP)
本文介绍了一款自定义输入框的实现,包含静态效果、hint值浮动动画及功能扩展。通过组合多个控件完成界面布局,使用TranslateAnimation与AlphaAnimation实现hint文字上下浮动效果,支持密码加密解密显示、去除键盘回车空格输入、光标定位等功能。代码基于Android平台,提供完整源码与attrs配置,方便复用与定制。希望对开发者有所帮助。
253 0
|
10月前
|
Android开发 Kotlin
|
10月前
|
运维 网络协议 安全
为什么经过IPSec隧道后HTTPS会访问不通?一次隧道环境下的实战分析
本文介绍了一个典型的 HTTPS 无法访问问题的排查过程。问题表现为 HTTP 正常而 HTTPS 无法打开,最终发现是由于 MTU 设置不当导致报文被丢弃。HTTPS 因禁止分片,对 MTU 更敏感。解决方案包括调整 MSS 或中间设备干预。
|
10月前
HTTP协议中请求方式GET 与 POST 什么区别 ?
GET和POST的主要区别在于参数传递方式、安全性和应用场景。GET通过URL传递参数,长度受限且安全性较低,适合获取数据;而POST通过请求体传递参数,安全性更高,适合提交数据。
874 2
|
Android开发 Windows
Android studio 报错Connect to 127.0.0.1:8888 [/127.0.0.1] failed: Connection refused: connect(已解决)
这是一篇关于解决Android Studio报错“Connect to 127.0.0.1:8888 failed: Connection refused”的文章。问题通常因系统代理设置被Android Studio自动保存导致。解决方法是找到系统中Android Studio使用的gradle.properties文件(位于Windows的C:\Users\你的电脑用户名\.gradle或Mac的/Users/.{你的用户目录}/.gradle),删除或注释掉多余的代理配置后保存并重新Sync项目。希望此经验能帮助快速解决同类问题!
2442 36
|
Java Android开发
Android studio中build.gradle文件简单介绍
本文解析了Android项目中build.gradle文件的作用,包括jcenter仓库配置、模块类型定义、包名设置及依赖管理,涵盖本地、库和远程依赖的区别。
1047 19
|
8月前
|
缓存 移动开发 JavaScript
如何优化UniApp开发的App的启动速度?
如何优化UniApp开发的App的启动速度?
1337 139
|
8月前
|
移动开发 JavaScript weex
UniApp开发的App在启动速度方面有哪些优势和劣势?
UniApp开发的App在启动速度方面有哪些优势和劣势?
594 137