package httpClient; import java.util.ArrayList; import java.util.List; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.HttpClient; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.message.BasicNameValuePair; import org.apache.http.util.EntityUtils; import net.sf.json.JSONObject; public class TestSendSMS { /** * @param args */ public static void main(String[] args) { String uid = "12345678"; String title = "test"; String content = "test a content"; String ret = sendSms(uid, title, content); System.out.println(ret); if (ret.indexOf("失败") < 0) { System.out.println("成功发送sms"); } else { System.out.println("失败发送"); } } public static String sendSms(String uid, String title, String content) { HttpClient httpclient = new DefaultHttpClient(); String smsUrl = "http://localhost:9000/index"; HttpPost httppost = new HttpPost(smsUrl); String strResult = ""; try { List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); JSONObject jobj = new JSONObject(); jobj.put("uid", uid); jobj.put("title", title); jobj.put("content", content); nameValuePairs.add(new BasicNameValuePair("msg", jobj.toString())); httppost.addHeader("Content-type", "application/x-www-form-urlencoded"); httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8")); HttpResponse response = httpclient.execute(httppost); if (response.getStatusLine().getStatusCode() == 200) { /* 读返回数据 */ String conResult = EntityUtils.toString(response.getEntity()); System.out.println(conResult); // JSONObject sobj = new JSONObject(); // sobj = sobj.fromObject(conResult); // String result = sobj.getString("result"); // String code = sobj.getString("code"); // if (result.equals("1")) { // strResult += "发送成功"; // } else { // strResult += "发送失败," + code; // } } else { String err = response.getStatusLine().getStatusCode() + ""; strResult += "发送失败:" + err; } } catch (Exception e) { e.printStackTrace(); } return strResult; } }