使用httpclient实现http接口调用实例
2015-08-25 00:00
746 查看
摘要: 使用httpclient实现http接口调用实例 httpclient
package com.yanek.test; import java.io.IOException; import java.util.ArrayList; import java.util.List; import net.sf.json.JSONObject; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.ClientProtocolException; 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; 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://192.168.0.1/service/sendsms"; 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", getStringFromJson(jobj))); 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()); 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 (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return strResult; } private static String getStringFromJson(JSONObject adata) { StringBuffer sb = new StringBuffer(); sb.append("{"); for(Object key:adata.keySet()){ sb.append("\""+key+"\":\""+adata.get(key)+"\","); } String rtn = sb.toString().substring(0, sb.toString().length()-1)+"}"; return rtn; } }
相关文章推荐
- RPC failed; result=22, HTTP code = 411
- fastjson处理接口时的一个问题
- HTTP Header 属性列表
- nginx中http核心模块的配置指令2
- 局域网与广域网接口标准
- RJ-45接口信号定义
- DVI 视频接口图文解析
- 深入HTTP head的使用详解
- ASP 中使用 HTTP 协议发送参数详解
- C#基于socket模拟http请求的方法
- http www安全必备知识
- 如何设置域名接口
- 通过C#实现自动售货机接口
- C#中IEnumerable接口用法实例分析
- C#中实现判断某个类是否实现了某个接口
- C#实现两接口中同名方法实例分析
- asp HTTP 500错误 常见问题分析
- C#中的ICustomFormatter及IFormatProvider接口用法揭秘