java以URL方式调用接口

        @Override
public Map realTimeSendXMLDataToServer(String content, String BWID) {
Map map = new HashMap();
URL url;
HttpURLConnection connet = null;
try {
url = new URL(Global.loadProperties("config.properties").getProperty("ServerURL"));
connet = (HttpURLConnection) url.openConnection();
connet.setDoInput(true);
connet.setDoOutput(true);
connet.setRequestMethod("POST");
connet.setConnectTimeout(20 * 1000);// 设置连接超时时间为5秒
connet.setReadTimeout(20 * 1000);// 设置读取超时时间为20秒
connet.setRequestProperty("Accept-Charset", "UTF-8");
connet.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
DataOutputStream doutstream = new DataOutputStream(connet.getOutputStream());
byte[] btsnew = content.getBytes("UTF-8");
doutstream.write(btsnew);
// 这种是以二进制方式传输
StringBuilder sb = new StringBuilder();
if (connet.getResponseCode() != 200) {
System.out.println("调用server端服务错误:"+connet.getResponseMessage());
sb.append("{\"success\":\"false\",\"info\":\"调用server端服务失败\"}");
} else {
BufferedReader brd = new BufferedReader(new InputStreamReader(connet.getInputStream(), "utf-8"));
String line;
while ((line = brd.readLine()) != null) {
sb.append(line);
}
brd.close();
}
JSONObject object = JSON.parseObject(sb.toString());
String tag = object.getString("success");
String info = object.getString("info");
if (!StringHelper.isEmpty(tag)) {
if ("TRUE".equals(tag.toUpperCase())) {
map.put("RESULT", "OK");
map.put("MSG", "项目数据实时上报成功!");
} else {
map.put("RSEULT", "ERROR");
map.put("MSG", info);
}
}
// 更改状态
} catch (Exception e) {
e.printStackTrace();
map.put("RESULT", "ERROR");
map.put("MSG", "项目数据实时上报失败!");
} finally {
if (connet != null) {
connet.disconnect();
}
}
return map;

}

将map集合转换为request可用的参数用于参数传递:

private String prepareParam(Map mp,String xmlcontent) throws UnsupportedEncodingException{
String urlParamStr = "";
// 将属性信息进行编码
for (Entry entry : mp.entrySet()) {
urlParamStr += entry.getKey() + "=" + URLEncoder.encode(entry.getValue().toString().trim(), "utf-8") + "&";
}
xmlcontent=xmlcontent.replaceAll("\\+", "%2B");
urlParamStr += "XMLCONTENT="+xmlcontent;
return urlParamStr;
}



你可能感兴趣的:(java,hibernate,spring,springMVC)