在Android开发中,经常需要通过网络与服务器进行数据交互。HTTP是一种常用的协议,它提供了一种简单的方式来进行网络通信。本篇学习笔记将介绍如何在Android应用中使用HTTP进行网络请求,包括GET和POST请求的实现。
添加网络权限
首先,在你的Android项目中,需要在AndroidManifest.xml文件中添加网络权限:
<uses-permission android:name="android.permission.INTERNET" />
发起 GET 请求
GET请求用于从服务器获取数据。在Android中,可以使用HttpURLConnection
或HttpClient
类来发起GET请求。下面以HttpURLConnection
为例,演示如何发起GET请求:
try {
// 创建URL对象
URL url = new URL("http://example.com/api/data");
// 打开连接
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// 设置请求方法为GET
connection.setRequestMethod("GET");
// 获取响应码
int responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
// 读取响应数据
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
StringBuilder response = new StringBuilder();
while ((line = reader.readLine()) != null) {
response.append(line);
}
reader.close();
// 处理响应数据
String responseData = response.toString();
// TODO: 根据需要进行处理,涉及数据解析
} else {
// 请求失败,处理错误
}
// 关闭连接
connection.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
数据解析:(留个空)
发起 POST 请求
POST请求用于向服务器提交数据。同样地,我们可以使用HttpURLConnection
或HttpClient
类来发起POST请求。下面以HttpURLConnection
为例,演示如何发起POST请求:
try {
// 创建URL对象
URL url = new URL("http://example.com/api/data");
// 打开连接
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// 设置请求方法为POST
connection.setRequestMethod("POST");
// 允许写入请求数据
connection.setDoOutput(true);
// 设置请求体数据
String postData = "username=test&password=123456";
OutputStream outputStream = connection.getOutputStream();
outputStream.write(postData.getBytes("UTF-8"));
outputStream.close();
// 获取响应码
int responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
// 读取响应数据,处理方式与GET请求相同
} else {
// 请求失败,处理错误
}
// 关闭连接
connection.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
这里一般请求接口服务使用json格式,以申请邮箱发件为例:(半成品,暂时没找到原因,但是按道理大概是可以的;失败:{"code":-1,"msg":"目标邮箱(tomail)不能为空","data":{}})
接口来源:
package com.example.firstproject.http;
import android.util.Log;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
public class Registersendcode {
public void sendemail(String email, String verificationCode) {
new Thread(new Runnable() {
@Override
public void run() {
try {
// 构建请求体数据
JSONObject jsonBody = new JSONObject();
jsonBody.put("ColaKey", "xxxx);
jsonBody.put("tomail", email);
jsonBody.put("fromTitle", "验证码");
jsonBody.put("subject", "这是一条验证码");
jsonBody.put("smtpCode", "xxxx");
jsonBody.put("smtpEmail", "[email protected]");
jsonBody.put("smtpCodeType", "163");
jsonBody.put("isTextContent", false);
jsonBody.put("content", "<div style='color: red'>你的验证码是:" + verificationCode + "</div>");
String requestBody = jsonBody.toString();
Log.e("Registersendcoce", requestBody);
// 设置接口URL
URL url = new URL("https://luckycola.com.cn/tools/customMail");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
// 设置请求方法为POST
conn.setRequestMethod("POST");
//必须设置允许输入输出
conn.setDoInput(true);
conn.setDoOutput(true);
// 设置请求头
conn.setRequestProperty("Content-Type", "application/json; utf-8");
conn.setRequestProperty("Accept", "application/json");
// 发送请求体数据
try (OutputStream os = conn.getOutputStream()) {
byte[] input = requestBody.getBytes(StandardCharsets.UTF_8);
os.write(input);
}
// 如果需要,可以读取响应体
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
StringBuffer response = new StringBuffer();
while ((line = reader.readLine()) != null) {
response.append(line);
}
reader.close();
Log.e("Registersendcode", "响应的东西:" + response.toString());
// 获取响应状态码
int responseCode = conn.getResponseCode();
Log.e("Registersendcode", "Response Code: " + responseCode);
conn.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
}
package com.example.firstproject.http;
import java.util.Random;
public class Code {
private StringBuilder code;
private void generateVerificationCode() {
// 定义验证码的长度
int length = 6;
// 定义可能出现的字符
String characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
// 创建随机数生成器
Random random = new Random();
// 生成验证码
code = new StringBuilder();
for (int i = 0; i < length; i++) {
code.append(characters.charAt(random.nextInt(characters.length())));
}
}
public String getcode(){
generateVerificationCode();
return code.toString();
}
}
private Registersendcode sendcode;
private Code verticode;
sendcode= new Registersendcode();
String email=emailEditText.getText().toString();
verticode=new Code();
sendcode.sendemail(email, verticode.getcode());
//在需要的地方使用,传入两个参数就可以
线程限制
需要注意的是,在Android中,网络请求通常需要在后台线程中执行,以避免阻塞主线程。如果你在主线程中执行网络请求,将会导致应用无响应或ANR(应用无响应)错误。你可以使用异步任务(AsyncTask)、线程池或者使用第三方库如OkHttp、Volley等来执行网络请求。