java中对字符串进行拼接,然后加上模版的地址,拼接式请求参数。就会完成邮件的发送
package a_mailDemo;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;
public class Test3 {
public static void main(String[] args) throws IOException {
//适用java发送http请求
//先把请求参数放入map,方便后续的url编码,拼接等操作
Map<String, String> map = new HashMap<String,String>();
map.put("apiUser", "lzbhnr_test_CMyzxt");
map.put("apiKey", "Het0bnSv1fK34RLV");
map.put("from", "lzbsdust@sina.com");
map.put("templateInvokeName", "test_template_active");
StringBuilder params = new StringBuilder();
Set<Entry<String, String>> entrySet = map.entrySet();
for(Entry<String,String> entry:entrySet){
String key = entry.getKey();
String value= entry.getValue();
params.append(key).append("=").append(value).append("&");
}
//删除最后多余的&
params.deleteCharAt(params.length()-1);
URL url = new URL("http://api.sendcloud.net/apiv2/mail/sendtemplate"); //发送模版邮件的
URLConnection conn = url.openConnection();//打开连接
conn.setDoOutput(true);//设置输出流为可用。post请求需要用到输出流
OutputStream output = conn.getOutputStream();
//把请求参数发送给sendcloud服务器,服务器收到请求以后,会向指定的收件人发送模版邮件
output.write(params.toString().getBytes());
//读取响应
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line = null;
StringBuilder result = new StringBuilder();
while((line = reader.readLine())!=null){
result.append(line);
}
System.out.println(result);
output.close();
reader.close();
}
}