httpclient作用
在java代码中,发送Http请求。通常用来实现远程接口调用。
pom依赖
<dependency>
<groupId>commons-httpclient</groupId>
<artifactId>commons-httpclient</artifactId>
<version>3.1</version>
</dependency>
下面是我请求别人的接口的代码
//部分包
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.commons.httpclient.HttpClient;
import net.sf.json.JSONObject;
public QueryResponseResult post(String lineName, String dataTime) {
HttpClient httpclient = new HttpClient();
PostMethod httpPost = new PostMethod("http://ip地址:端口/computer");
if (lineName != null && dataTime != null) {
//设置参数
NameValuePair[] param = {new NameValuePair("lineName", lineName), new NameValuePair("dataTime", dataTime)};
//解决中文乱码
httpPost.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "utf-8");
httpPost.setRequestBody(param);
}
try {
//发送请求
httpclient.executeMethod(httpPost);
InputStream stream = httpPost.getResponseBodyAsStream();
BufferedReader br = new BufferedReader(new InputStreamReader(stream));
StringBuilder stringBuilder = new StringBuilder();
String str1 = "";
while ((str1 = br.readLine()) != null) {
stringBuilder.append(str1);
}
String sb = stringBuilder.toString();
//按照utf-8格式输出响应体
String result = new String(sb.getBytes(), StandardCharsets.UTF_8);
JSONObject fromObject = JSONObject.fromObject(result);
Object code = fromObject.get("code");
if ("500".equals(code.toString())) {
return new QueryResponseResult(CommonCode.ERROR, null);
} else if ("200".equals(code.toString())) {
Object data = fromObject.get("queryResult");
QueryResult queryResult = new QueryResult<>();
ArrayList<Map<String, Object>> list = new ArrayList<>();
Map<String, Object> map = new HashMap<>();
map.put("data", data);
list.add(map);
queryResult.setList(list);
return new QueryResponseResult(CommonCode.SUCCESS, queryResult);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
httpPost.releaseConnection();
}
return null;
}
附上返回数据
{
"code": "200",
"msg": "xxxxxxx",
"data": {
"dataTime": "2019-12-06 11:15:00",
"desc": "计算结果收敛",
"pflowLineDataList": [
{
"lineName": "xxxx",
"measuredActive": 0,
"measuredReactive": 0,
"calculateActive": -15.6,
"calculateReactive": 44.1
}
]
}
}