Http协议是在web开发中用到最多的协议了!访问我们发布的web服务都是通过js显式进行访问,但有时候为了访问安全,我们不能暴露访问的url地址及其登录信息,这时候,通过后台来实现post和get请求则是必须的了,最常见的应用就是短信发送,邮件服务等。
首先练习一下client的使用:
//上传文件到指定url地址
public static String doUploadFile(String postUrl) {
if(StringUtils.isEmpty(postUrl)){
return null;
}
String response="";
//使用post方式进行上传
PostMethod postMethod=new PostMethod(postUrl);
try{
//1.定义httpclient对象
HttpClient client=new HttpClient();
//2.文件上传可能需要很长时间,设定连接时间
client.getHttpConnectionManager().getParams().setConnectionTimeout(50000);
//3.执行post请求,返回状态码
int stauts=client.executeMethod(postMethod);
if(Status==HttpStatus.SC_OK){
//4.将responseBody打印输出
InputStream inputStream=postMethod.getResponseBodyAsStream();
BufferedReader br=new BufferredReader(new InputStreamReader(inputStream));
StringBuffer stringBuffer=new StringBuffer();
String str="";
while((str=br.readLine())!=null){
stringBuffer.append(str);
}
response=stringBuffer.toString();
}else{
response="fail";
}
}catch(Exception e){
e.printStackTrace();
}finally{
postMethod.releaseConnection();
}
return response;
}
@Service
public class ChuanglanSendMessageService{
private String un; //API账户
private String pw; //API账户密码
private String url; //服务地址
private String rd; //返回值是否需要返回状态报告:1-返回;0-不需要
public ChuanglanSendMessageService(){
this.un="注册用户名";
this.pw="设置密码";
this.url="http://sms.253.com/msg/";
this.rd="1";
}
/**
* @Description: 创蓝发送短信验证码
* @param phone 电话号码
* @param msg 发型消息内容
* @param ex 可选参数,扩展码,用户定义扩展码,扩展码的长度将直接影响短信上行接收的接收。固需要传扩展码参数时,请提前咨询客服相关设置问题。
* @throws Exception
* @return String
* @author haipeng
*/
public String batchSend(String phone,String msg, String ex) throws Exception {
//定义client对象
HttpClient client = new HttpClient(new HttpClientParams(), new SimpleHttpConnectionManager(true));
//要执行的method方法
GetMethod method = new GetMethod();
try {
URI base = new URI(url, false);
//拼接发送短信的url地址
method.setURI(new URI(base, "send", false));
//设置短信发送条件
method.setQueryString(new NameValuePair[] {
new NameValuePair("un", un),
new NameValuePair("pw", pw),
new NameValuePair("phone", phone),
new NameValuePair("rd", rd),
new NameValuePair("msg", msg),
new NameValuePair("ex", ex),
});
//获得方法执行返回码
int result = client.executeMethod(method);
if (result == HttpStatus.SC_OK) {
InputStream in = method.getResponseBodyAsStream();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
while ((len = in.read(buffer)) != -1) {
baos.write(buffer, 0, len);
}
return URLDecoder.decode(baos.toString(), "UTF-8");
} else {
throw new Exception("HTTP ERROR Status: " + method.getStatusCode() + ":" + method.getStatusText());
}
} finally {
method.releaseConnection();
}
}
}
参考文章: