package com.greenorange.promotion.utils.codec;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import java.util.ArrayList;
import java.util.List;

public class sendsms {

	private static String Url = "http://106.ihuyi.com/webservice/sms.php?method=Submit";

	public static void main(String[] args) {

		// 创建 HttpClient
		try (CloseableHttpClient client = HttpClients.createDefault()) {
			// 创建 POST 请求
			HttpPost post = new HttpPost(Url);
			post.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=GBK");

			// 生成验证码
//			int mobile_code = (int) ((Math.random() * 9 + 1) * 100000);
			int mobile_code = 114514;
			String content = "您的验证码是：" + mobile_code + "。请不要把验证码泄露给其他人。";

			// 设置请求参数
			List<NameValuePair> data = new ArrayList<>();
			data.add(new BasicNameValuePair("account", "C08121984"));
			data.add(new BasicNameValuePair("password", "84a27a879413ec629bf26c5d84a25271"));
			data.add(new BasicNameValuePair("mobile", "19804561639"));
			data.add(new BasicNameValuePair("content", content));

			// 设置请求体
			UrlEncodedFormEntity entity = new UrlEncodedFormEntity(data, "GBK");
			post.setEntity(entity);

			// 执行请求
			String response = client.execute(post, httpResponse -> {
				HttpEntity entity1 = httpResponse.getEntity();
				return EntityUtils.toString(entity1, "GBK");
			});

			// 解析返回的 XML 响应
			Document doc = DocumentHelper.parseText(response);
			Element root = doc.getRootElement();

			String code = root.elementText("code");
			String msg = root.elementText("msg");
			String smsid = root.elementText("smsid");

			System.out.println(code);
			System.out.println(msg);
			System.out.println(smsid);

			if ("2".equals(code)) {
				System.out.println("短信提交成功");
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
