httpclient 调取接口_使用httpclient实现http接口调用实例

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 nameValuePairs = new ArrayList();

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;

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值