发送请求的大致过程如下:
String url=" http://www.baidu.com ";
HttpPost httppost=new HttpPost(url); //建立HttpPost对象
List<NameValuePair> params=new ArrayList<NameValuePair>(); //建立一个NameValuePair数组,用于存储欲传送的参数
params.add(new BasicNameValuePair("pwd","2544"));//添加参数
httppost.setEntity(new UrlEncodedFormEntity(params,HTTP.UTF_8)); //设置编码
HttpResponse response=new DefaultHttpClient().execute(httppost); //发送Post,并返回一个HttpResponse对象
完整的向url发送post请求带参数代码
public static String searchUrl = "http://192.168.0.90:9999/ml/predict_credit";
final CloseableHttpClient httpClient = HttpClients.createDefault();
final HttpPost httpPost = new HttpPost(searchUrl);
final List<BasicNameValuePair> pairList = new ArrayList<>();
pairList.add(new BasicNameValuePair("客户编码", map.get("consumerCode")));
pairList.add(new BasicNameValuePair("借款人行业", map.get("jobIndustry")));
CloseableHttpResponse response = null;
try {
httpPost.setEntity(new UrlEncodedFormEntity(pairList, "utf-8"));
response = httpClient.execute(httpPost);
final HttpEntity httpEntity = response.getEntity();
final ObjectMapper mapper = new ObjectMapper();
@SuppressWarnings("unchecked")
final Map<String, Object> values = mapper.readValue(httpEntity.getContent(), Map.class);
LOGGER.info("[ML result]:" + values);
return values;
} catch (final Exception e) {
LOGGER.debug("execute httpPost error");
return null;
} finally {
try {
response.close();
httpClient.close();
} catch (final Exception e) {
LOGGER.debug("Http client close error.");
throw new RuntimeException(e);
}
}
}