import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.Header;
import org.apache.http.NameValuePair;
import org.apache.http.StatusLine;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
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;
public class SendMsg_webchinese {
public static final String UID = "123";
public static final String KEY = "123456";
public static final String SMS_SEND_URI = "http://utf8.sms.webchinese.cn";
public static final String SMS_NUM_URI = "http://sms.webchinese.cn/web_api/SMS/?Action=SMS_Num";
// 发送短信
public static int sendMessage(String phone, String smsText) throws IOException{
HttpPost post = new HttpPost(SMS_SEND_URI);
List<NameValuePair> list = new ArrayList<NameValuePair>();
list.add(new BasicNameValuePair("smsMob", phone));
list.add(new BasicNameValuePair("smsText", smsText));
String result = executeMethod(post, list);
System.out.println("发送短信数量:" + result + ",手机号:" + phone + "信息:" + smsText);
return Integer.parseInt(result);
}
// 获取短信数量
public static int smsNum() throws IOException{
HttpPost post = new HttpPost(SMS_NUM_URI);
List<NameValuePair> list = new ArrayList<NameValuePair>();
String result = executeMethod(post, list);
System.out.println("短信数量:" + result);
return Integer.parseInt(result);
}
private static String executeMethod(HttpPost post, List<NameValuePair> list) throws IOException{
list.add(new BasicNameValuePair("Uid", UID));
list.add(new BasicNameValuePair("Key", KEY));
post.setEntity(new UrlEncodedFormEntity(list, "UTF-8"));
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse httpResponse = null;
String result = "-1";
try {
httpResponse = httpClient.execute(post);
Header[] headers = httpResponse.getAllHeaders();
StatusLine statusLine = httpResponse.getStatusLine();
System.out.println("statusLine:" + statusLine);
for (Header h : headers) {
System.out.println(h);
}
result = EntityUtils.toString(httpResponse.getEntity());
} catch (IOException e) {
} finally {
post.releaseConnection();
if(httpResponse != null) httpResponse.close();
httpClient.close();
}
return result;
}
}
由于官网提供的发短信为httpclient3.1版本,apache不再支持,改成apache最新版的httpclient