最近需要将Android 项目接入物联网公司提供的接口,所以顺便给大家分享一下Android中我们常用的网络请求吧!提醒大家一下,我们遇到接口需求,一定要先在Postman上测试接口是否正确,然后再去项目上写程序来请求接口;否则,请求出问题,你都不确定是你程序写的有问题还是接口本身提供的有问题。
这是 Android 中最常用的网络请求方式,可以通过该类建立连接并进行 HTTP 请求和响应的读写操作。使用简单,支持多种数据格式。
public void sendGetRequest() {
String url = "http://example.com/api/getData";
HttpURLConnection connection = null;
try {
URL requestUrl = new URL(url);
connection = (HttpURLConnection) requestUrl.openConnection();
connection.setRequestMethod("GET");
// 添加header
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("Accept", "application/json");
// 设置连接和读取超时时间
connection.setConnectTimeout(8000);
connection.setReadTimeout(8000);
int responseCode = connection.getResponseCode();
if (responseCode == 200) { // 请求成功
InputStream inputStream = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder builder = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
builder.append(line);
}
String response = builder.toString();
Log.d(TAG, "response: " + response);
} else { // 请求失败
Log.e(TAG, "Error response code: " + responseCode);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
}
}
其中,我们使用HttpURLConnection的openConnection()方法打开一个连接,然后设置请求方式为GET,再添加headers,设置连接和读取超时时间,最后通过getResponseCode()方法获取响应码,如果是200则表示请求成功,接着就可以获取响应数据了。
public class MainActivity extends AppCompatActivity {
private EditText editText;
private TextView textView;
private String url = "http://example.com/api";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText = findViewById(R.id.editText);
textView = findViewById(R.id.textView);
Button button = findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String postData = editText.getText().toString().trim();
if (!TextUtils.isEmpty(postData)) {
new PostTask().execute(postData);
} else {
Toast.makeText(MainActivity.this, "请输入内容", Toast.LENGTH_SHORT).show();
}
}
});
}
private class PostTask extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... params) {
try {
URL reqUrl = new URL(url);
HttpURLConnection conn = (HttpURLConnection) reqUrl.openConnection();
conn.setReadTimeout(10000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
OutputStream outputStream = conn.getOutputStream();
outputStream.write(params[0].getBytes("UTF-8"));
outputStream.flush();
outputStream.close();
int responseCode = conn.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
InputStream inputStream = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
StringBuilder response = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
response.append(line);
}
reader.close();
inputStream.close();
return response.toString();
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(String result) {
if (result != null) {
textView.setText(result);
} else {
Toast.makeText(MainActivity.this, "请求出错", Toast.LENGTH_SHORT).show();
}
}
}
}
Volley 是 Google 推出的一款网络请求框架,专门用于简化 Android 应用开发中的网络请求,具有自动请求队列、网络请求缓存、图片加载等功能。
// 创建一个 RequestQueue 对象
RequestQueue queue = Volley.newRequestQueue(this);
// 指定请求的 URL
String url = "https://www.example.com/api/get_data";
// 创建一个 StringRequest 对象
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
// 响应成功时的回调函数
Log.d(TAG, "Response: " + response);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
// 响应失败时的回调函数
Log.e(TAG, "Error: " + error.getMessage());
}
});
// 将 StringRequest 对象添加到 RequestQueue 中
queue.add(stringRequest);
RequestQueue queue = Volley.newRequestQueue(this);
String url = "http://your-url.com/post-endpoint";
StringRequest postRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>()
{
@Override
public void onResponse(String response) {
// 处理响应
}
},
new Response.ErrorListener()
{
@Override
public void onErrorResponse(VolleyError error) {
// 处理错误
}
}
) {
@Override
protected Map<String, String> getParams()
{
// 请求参数
Map<String, String> params = new HashMap<String, String>();
params.put("param1", "value1");
params.put("param2", "value2");
return params;
}
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap<String, String>();
// 添加headers
headers.put("Authorization", "Bearer your-access-token");
return headers;
}
};
queue.add(postRequest);
Retrofit 是一个基于 OkHttp 的类型安全的 RESTful 客户端,可以使用注解的方式实现接口的定义,高效易用,支持多种数据格式。
1. 添加Retrofit依赖项:在您的Android项目中的build.gradle文件中添加以下依赖项:
dependencies {
implementation 'com.squareup.retrofit2:retrofit:2.9.0'
implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
}
2. 创建Retrofit实例:在您的Java类中创建Retrofit实例。
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://yourapi.com/")
.addConverterFactory(GsonConverterFactory.create())
.build();
3. 创建API接口:创建一个Java接口,其中定义GET请求以及其参数和返回类型。
public interface YourApiService {
@GET("your_api_path")
Call<YourApiResponse> getYourApiData(@Query("your_param_name") String yourParamValue);
}
4. 发送GET请求:在您的Java类中使用Retrofit实例创建API服务实例,并发送GET请求。这可以在Activity或Fragment中完成,也可以使用ViewModel和LiveData进行MVVM架构。
YourApiService apiService = retrofit.create(YourApiService.class);
Call<YourApiResponse> call = apiService.getYourApiData("your_param_value");
call.enqueue(new Callback<YourApiResponse>() {
@Override
public void onResponse(Call<YourApiResponse> call, Response<YourApiResponse> response) {
// 处理响应
}
@Override
public void onFailure(Call<YourApiResponse> call, Throwable t) {
// 处理失败
}
});
在上面的代码中,我们使用enqueue()方法异步发送GET请求,并在回调方法中处理响应。我们可以在onResponse()方法中处理成功的响应,并在onFailure()方法中处理失败的响应。
使用Retrofit发送POST请求需要创建一个接口,接口中定义请求的参数和返回值类型,在方法上使用@POST注解,并且指定请求的URL,参数使用@Body注解标识。下面是一个简单的示例:
首先,添加Retrofit的依赖:
implementation 'com.squareup.retrofit2:retrofit:2.9.0'
然后,定义一个接口,例如:
public interface ApiInterface {
@POST("login")
Call<ResponseBody> login(@Body LoginRequest request);
}
其中,@POST("login")表示请求的URL为"login",@Body LoginRequest request表示请求的参数为一个LoginRequest对象。
接下来,创建一个Retrofit实例,并调用接口中的请求方法,例如:
//创建Retrofit实例
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
//创建接口实例
ApiInterface apiInterface = retrofit.create(ApiInterface.class);
//创建请求对象
LoginRequest request = new LoginRequest("username", "password");
//发送请求
Call<ResponseBody> call = apiInterface.login(request);
call.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
//请求成功处理逻辑
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
//请求失败处理逻辑
}
});
其中,BASE_URL需要替换为你的服务器地址,LoginRequest为请求参数的实体类,例如:
public class LoginRequest {
private String username;
private String password;
public LoginRequest(String username, String password) {
this.username = username;
this.password = password;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
以上就是通过Retrofit发送POST请求的基本流程。
OkHttp 是一个高效的 HTTP 客户端,支持 HTTP/2 和持久连接,可以用于替代 HttpUrlConnection 和 Volley。
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url("https://www.example.com/get")
.build();
try {
Response response = client.newCall(request).execute();
String responseData = response.body().string();
Log.d(TAG, "onResponse: " + responseData);
} catch (IOException e) {
e.printStackTrace();
}
以下是一个使用OkHttp同步发送POST请求的示例代码:
OkHttpClient client = new OkHttpClient();
// 构造请求体,这里使用JSON格式
String json = "{\"username\":\"admin\",\"password\":\"123456\"}";
RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), json);
// 构造请求对象
Request request = new Request.Builder()
.url("http://www.example.com/login") // 请求URL
.addHeader("Content-Type", "application/json") // 设置请求头
.post(requestBody) // 设置请求体
.build();
// 创建Call对象并发起请求
Call call = client.newCall(request);
Response response = call.execute();
// 解析响应结果
String result = response.body().string();
需要注意的是,如果请求过程需要很长时间,建议使用enqueue方法异步发起请求,避免阻塞主线程。例如:
OkHttpClient client = new OkHttpClient();
// 构造请求体
String json = "{\"username\":\"admin\",\"password\":\"123456\"}";
RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), json);
// 构造请求对象
Request request = new Request.Builder()
.url("http://www.example.com/login") // 请求URL
.addHeader("Content-Type", "application/json") // 设置请求头
.post(requestBody) // 设置请求体
.build();
// 创建Call对象并异步发起请求
Call call = client.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
// 处理请求失败的情况
}
@Override
public void onResponse(Call call, Response response) throws IOException {
// 处理响应结果
String result = response.body().string();
}
});
AsyncHttpClient 是一个轻量级的异步 HTTP 客户端,支持 HTTP、HTTPS、WebSocket 和 HTTP2.0 协议,可以实现全局的请求头和请求参数的设置。
AsyncHttpClient client = new AsyncHttpClient();
String url = "https://www.example.com/api/data";
RequestParams params = new RequestParams();
params.put("param1", "value1");
params.put("param2", "value2");
client.get(url, params, new AsyncHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
// 请求成功
String response = new String(responseBody);
Log.d("AsyncHttpClient", "Response: " + response);
}
@Override
public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
// 请求失败
Log.e("AsyncHttpClient", "Error: " + error.getMessage());
}
});
String url = "http://example.com/api/post";
client.post(url, params, new AsyncHttpResponseHandler() {
@Override
public void onStart() {
// 发送请求前调用
}
@Override
public void onSuccess(int statusCode, Header[] headers, byte[] response) {
// 请求成功调用, statusCode为HTTP状态码
String result = new String(response);
Log.i(TAG, "onSuccess: " + result);
}
@Override
public void onFailure(int statusCode, Header[] headers, byte[] errorResponse, Throwable e) {
// 请求失败调用,statusCode为HTTP状态码
Log.e(TAG, "onFailure: statusCode=" + statusCode, e);
}
@Override
public void onRetry(int retryNo) {
// 请求重试调用
}
});
文章浏览阅读1.5w次,点赞35次,收藏385次。自己在网上找的开源项目,比较好分享给大家热门开源项目(包含小四轴、智能手环、光立方、智能车、防丢器等项目)号外!号外!(搞四轴,有这套就足够了!)科研级别的小四轴STM32F4芯片支持WIFI且android手机控制自适应控制就是牛掰!该飞机面向有科研和强烈学习意向的小伙伴们使用,如果只是想玩的话你肯定不会喜欢这套四轴的,主要设计思想是提供一个高性能的控制和姿态算法验证平台,因此..._本科毕业设计拿别人的开源代码修改
文章浏览阅读1w次,点赞2次,收藏26次。QQ 1274510382Wechat JNZ_aming商业联盟 QQ群538250800技术搞事 QQ群599020441解决方案 QQ群152889761加入我们 QQ群649347320共享学习 QQ群674240731纪年科技aming网络安全 ,深度学习,嵌入式,机器强化,生物智能,生命科学。叮叮叮:产品已上线 —>关注 官方-微信公众号——济南纪年信息科技有限公司民生项目:商城加盟/娱乐交友/创业商圈/外包兼职开发-项目发布/安全项目:态势感.._ruoyi java17
文章浏览阅读9k次,点赞2次,收藏3次。 当利用Console口为交换机设置好IP地址信息并启用HTTP服务后,即可通过支持JAVA的Web浏览器访问交换机,并可通过Web通过浏览器修 改交换机的各种参数并对交换机进行管理。事实上,通过Web界面,可以对交换机的许多重要参数进行修改和设置,并可实时查看交换机的运行状态。不过在利用 Web浏览器访问交换机之前,应当确认已经做好以下准备工作:·在用于管理的计算机中安装T..._思科交换机2960s有web配置吗
文章浏览阅读2.5w次,点赞2次,收藏6次。报错信息: [2018-09-09 20:33:12] ERROR - file: tracker_proto.c, line: 48, server: 127.0.0.1:22122, response status 2 != 0 [2018-09-09 20:33:12] ERROR - file: tracker_proto.c, line: 48, server: 127.0.0.1:..._error - file: tracker_proto.c, line: 48, server: 172.17.0.1:22122, response
文章浏览阅读3.9k次。使用matplotlib显示图片(《深度学习入门:基于Python的理论与实现》实践笔记)一、安装matplotlib库二、导入matplotlib.pyplot库和matplotlib.image库里的imread函数三、实例:显示图片一、安装matplotlib库在命令行使用下面的命令即可:pip install matplotlib二、导入matplotlib.pyplot库和matplotlib.image库里的imread函数在程序开头使用:import matplotlib.pyp_matplotlib展示图片
文章浏览阅读1.2k次。基本信息 用户单位:某应用软件研发企业 用户规模:100人以上 组织过程水平:中等 CMMI评审等级:无 Subversion使用时间:1年 客户需求 由于公司每次向新客户提交软件的时候都需要派出一个小规模的团队到客户现场进行一段时间的软件定制和维护。此外,老客户系统的重大升级和功能扩展也需要一个小团队在客户现场进行一段时间的开发。因此,异地开发的配置管理就是一_开发去客户现场的案例
文章浏览阅读3.2k次。一定时宽的语音信号,其能量的大小随时间有明显的变化。清音段能量比浊音段小得多。短时过零数也可用于语音信号分析中,发浊音时,其语音能量约集中于3kHz以下,而发清音时,多数能量出现在较高频率上。可认为浊音时具有较低的平均过零数,而清音时具有较高的平均过零数,故对一短时语音段计算其短时平均能量及短时平均过零数,就可以区分其中的清音段和浊音段,从而可判别句中清、浊音转变时刻,声母韵母的分界以及无声与有声的分界。这在语音识别中有重要意义。自己编写的matlab代码,对一段语音,取帧长为240个点,计算其平均能_matlab求语音信号短时过零率的函数
默认情况下,在Ubuntu上,sudo组的成员被授予sudo访问权限。如果您希望新创建的用户具有管理权限,需要将将用户添加到sudo组。命令将向你询问一系列的问题。密码是必需的,其他字段都是可选的。最后,输入Y确认信息是否正确。执行完上述步骤后需要重启ssh服务,否则新创建的用户连接服务器时会出现。
文章浏览阅读1.7k次。组织战略是组织实施各级项目管理,包括项目组合管理、项目集管理和项目管理的基础。只有从组织战略的高度来思考,思考各个层次项目管理在组织中的位置,才能够理解各级项目管理在组织战略实施中的作用。同时战略管理也为项目管理提供了具体的目标和依据,各级项目管理都需要与组织的战略保持一致。..._项目组织的具体形态的是战略管理层
文章浏览阅读1k次。目录基本统计量色彩空间变换亮度变换函数白平衡图像过曝的评价指标多视影像因曝光条件不一而导致色彩差异,人眼可以快速区分影像质量,如何利用图像信息辅助算法判断影像优劣。基本统计量灰度均值方差梯度均值方差梯度幅值直方图图像熵p·log(p)色彩空间变换RGB转单通道灰度图像 mean = 225.7 stddev = 47.5mean = 158.5 stddev = 33.2转灰度梯度域gradMean = -0.0008297 / -0.000157461gr_图像颜色质量评价
文章浏览阅读1.4k次。Simpson's rule for numerical integrationZ = SIMPS(Y) computes an approximation of the integral of Y via the Simpson's method (with unit spacing). To compute the integral for spacing different from one..._matlab利用幸普生计算积分
文章浏览阅读1.2w次,点赞28次,收藏61次。Hugging face 资源很不错,可是国内下载速度很慢,动则GB的大模型,下载很容易超时,经常下载不成功。很是影响玩AI的信心。经过多次测试,终于搞定了下载,即使超时也可以继续下载。真正实现下载无忧!究竟如何实现?且看本文分解。_huggingface_hub