package com.medicalsystem.service.impl;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.UsernamePasswordCredentials;
import org.apache.commons.httpclient.auth.AuthScope;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.medicalsystem.service.SendMailService;
public class SendMailServiceImpl implements SendMailService {
@Override
public void sendMail(String content) {
HttpClient httpClient = new HttpClient();
String url = "http://localhost:8081/receive";
//需要验证
UsernamePasswordCredentials creds = new UsernamePasswordCredentials("ross", "ross");
httpClient.getState().setCredentials(AuthScope.ANY,creds);
//设置http头
List <Header> headers = new ArrayList <Header>();
headers.add(new Header("User-Agent", "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)"));
httpClient.getHostConfiguration().getParams().setParameter("http.default-headers", headers);
PostMethod postMethod = new PostMethod(url);
JSONObject json = new JSONObject();
json.put("content", content);
json.put("createDate", new Date());
// json.put("to", "115719089@qq.com");
// json.put("from", "115719089@qq.com");
try {
postMethod.setRequestEntity(new StringRequestEntity(JSON.toJSONString(json),null,"utf-8"));
int statuCode = httpClient.executeMethod(postMethod);
if(statuCode == 200){
System.out.println("发送成功,邮件内容:"+content);
postMethod.getParams().setContentCharset("utf-8");
String a = postMethod.getResponseBodyAsString();
System.out.println(a);
}
} catch (HttpException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
postMethod.releaseConnection();
}
}
/**
* 测试
* @param args
*/
public static void main(String[] args) {
SendMailServiceImpl service = new SendMailServiceImpl();
service.sendMail("12是的");
// service.sendMail("zhangsan");
// service.sendMail("lisi");
}
}
httpclient post请求,需要登录的地址
最新推荐文章于 2022-09-03 13:34:46 发布