您的位置:首页 > 理论基础 > 计算机网络

利用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;
} 阅读更多
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: