http协议调用接口并反馈消息的小例子

时间:2022-10-14 17:54:34

import java.io.IOException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;


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.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


import com.sun.corba.se.spi.orb.StringPair;
import com.utstar.sobeyadapter.dao.AssetidmapDao;
import com.utstar.sobeyadapter.dao.CtmsEventDao;
import com.utstar.sobeyadapter.domain.Assetidmap;
import com.utstar.sobeyadapter.domain.CategoryResponse;
import com.utstar.sobeyadapter.domain.Constant;
import com.utstar.sobeyadapter.domain.CtmsServiceEvent;
import com.utstar.sobeyadapter.domain.ResponseObject;
import com.utstar.sobeyadapter.util.BeanHelper;
import com.utstar.sobeyadapter.util.SpringContextHolder;


import net.sf.json.JSONObject;

public static void sendResponseMessage(JSONObject jsonParam) {

// post请求返回结果
HttpClient httpClient = HttpClients.createDefault();
JSONObject jsonResult = null;
String url = Constant.ExternalResponseUrl;
logger.info("反馈消息的URL为:"+url);
HttpPost method = new HttpPost(url);
try {
if (null != jsonParam) {
// 解决中文乱码问题
StringEntity entity = new StringEntity(jsonParam.toString(), "UTF-8");
entity.setContentEncoding("UTF-8");
entity.setContentType("application/json");
method.setHeader("Content-Type", "application/json; charset=UTF-8");
method.setEntity(entity);
}
HttpResponse result = httpClient.execute(method);
url = URLDecoder.decode(url, "UTF-8");
/** 请求发送成功,并得到响应 **/
if (result.getStatusLine().getStatusCode() == 200) {
logger.info("处理内部工单后反馈处理结果消息:"+jsonParam);

/* String str = "";
try {
*//** 读取服务器返回过来的json字符串数据 **//*
// str = EntityUtils.toString(result.getEntity());
str =EntityUtils.toString(result.getEntity(), "UTF-8");
if (noNeedResponse) {
return;
}
*//** 把json字符串转换成json对象 **//*
// jsonResult = JSONObject.fromObject(str);
logger.info("----------------------发送返回消息成功:"+str);
} catch (Exception e) {
logger.error("post请求提交失败:" + url, e);
}*/
}
} catch (IOException e) {
logger.error("post请求提交失败:" + url, e);
}
}