Java发送接口通常指的是通过HTTP请求发送数据到远程服务器。以下是一个使用Java的HttpClient库发送HTTP POST请求的示例代码:
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
public class ApiClient {
// 短信发送接口的http地址,请咨询客服
private static String url = "xxxxxxxxxxxxxxxxxxxxxxxxxxxx";
// 编码格式,发送编码格式统一用UTF-8
private static String ENCODING = "UTF-8";
public static void main(String[] args) throws IOException, URISyntaxException {
// 账号
String account = "您的账号";
// 密码
String pswd = "您的密码";
// 修改为您要发送的手机号,多个用逗号分割
String mobile = "13*";
// 设置您要发送的内容
String msg = "【秒赛科技】您的验证码是:1234";
// 创建HttpClient实例
HttpClient httpClient = new HttpClient();
// 创建PostMethod实例
PostMethod postMethod = new PostMethod(url);
// 设置请求头,指定编码格式
postMethod.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=" + ENCODING);
// 设置请求参数
NameValuePair[] parameters = {
new NameValuePair("account", account),
new NameValuePair("pswd", pswd),
new NameValuePair("mobile", mobile),
new NameValuePair("msg", msg)
};
postMethod.setRequestBody(parameters);
// 执行请求
int statusCode = httpClient.executeMethod(postMethod);
// 输出响应状态码
System.out.println("Response Code: " + statusCode);
// 关闭连接
postMethod.releaseConnection();
}
}
请注意,上述代码示例中的`url`、`account`、`pswd`、`mobile`和`msg`需要替换为实际的值。此外,根据您要发送数据的接口要求,可能还需要设置其他的请求头或请求体内容。
如果您需要发送的是邮件,可以使用JavaMail API,如下所示:
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;
public class MailDemo01 {
public static void main(String[] args) {
try {
// 设置邮件服务器
Properties properties = new Properties();
properties.put("mail.smtp.host", "smtp..com");
properties.put("mail.smtp.port", "587");
properties.put("mail.smtp.auth", "true");
properties.put("mail.smtp.starttls.enable", "true");
// 获取默认的Session对象
Session session = Session.getDefaultInstance(properties, new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("您的邮箱地址", "授权码");
}
});
// 创建MimeMessage对象
MimeMessage message = new MimeMessage(session);
// 设置发件人
message.setFrom(new InternetAddress("您的邮箱地址"));
// 添加收件人
message.addRecipient(Message.RecipientType.TO, new InternetAddress("收件人邮箱地址"));
// 设置邮件主题和内容
message.setSubject("邮件主题");
message.setText("邮件内容");
// 发送邮件
Transport.send(message);
System.out.println("邮件发送成功!");
} catch (MessagingException e) {
e.printStackTrace();
}
}
}
请确保替换`您的邮箱地址`和`授权码`为实际的值,并且根据实际需要调整邮件内容和收件人信息。