利用httpClient根据地址和端口号调用web服务
2018-03-27 14:56
543 查看
应用场景:在如spring boot等构建的web 应用程序后台调用服务时可以用这种方式,工具:httpclinet-4.5.3.jar
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreConnectionPNames;
import org.json.JSONException;
import org.json.JSONObject;
public class HttpClientGatWay {
public static String url = "http://127.0.0.1:8080/Transaction";/**
*
* @param jsonObj 请求报文
* @param url 请求地址
* @return 如果请求出错则返回null,否则返回返回报文
*/
public static JSONObject httpPostWithJson(JSONObject jsonObj, String url) {
JSONObject retJobj=null;
HttpPost post = null;
try {
HttpClient httpClient = new DefaultHttpClient();
// 设置超时时间
httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 2000);
httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 2000);
post = new HttpPost(url);
// 构造消息头
post.setHeader("Content-type", "application/json; charset=utf-8");
post.setHeader("Connection", "Close");
// 构建消息实体
StringEntity entity = new StringEntity(jsonObj.toString(), Charset.forName("UTF-8"));
entity.setContentEncoding("UTF-8");
// 发送Json格式的数据请求
entity.setContentType("application/json");
post.setEntity(entity);
HttpResponse response = httpClient.execute(post);
// 检验返回码
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
return null;
}else{
BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null) {
sb.append(line + NL);
}
in.close();
String content = sb.toString();
retJobj=new JSONObject(content);
}
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
if (post != null) {
try {
post.releaseConnection();
} catch (Exception e) {
e.printStackTrace();
}
}
}
return retJobj;
} 阅读更多
相关文章推荐
- 利用广播调用后台服务方法并根据方法返回的内容更新UI
- 利用axis2调用远程WEB服务,获取天气预报
- 如何利用 SSL 调用 Web 服务
- 经典技术文章转载:如何利用 SSL 调用 Web 服务
- WF工作流与Web服务的相互调用 —— WF与WCF互相调用(利用ReceiveActivity把WF发布为WCF)
- C# 根据地址调用 Google Map 服务得到经纬度
- 使用HttpClient调用RESTful Web服务
- XFire 下载地址,java调用web服务
- WCF服务返回JSON格式数据、配置web调用地址
- 通过 Jersey 客户端 API 调用 REST 风格的 Web 服务
- 从 ASPX 页面进行 Web 服务调用时的性能考虑
- ASPX页Web服务调用性能优化
- 使用 AJAX 调用 SOAP Web 服务
- COM(VB/VBA/Script)利用服务标记调用WCF服务之三使用WSDL契约
- 动态调用web服务
- sqlserver 调用qq map 服务,根据地点获取所在城市
- 利用WEB服务在网页中插入天气预报功能
- axis2 客户端调用wss4j 安全web服务的方法
- C#动态调用Web服务的3种方法
- Web服务下的异步调用