1放棒、當(dāng)需要使用其他公司的接口時(shí)姻报,前臺(tái)很可能出現(xiàn)跨域問(wèn)題,此時(shí)就需要后臺(tái)發(fā)送url請(qǐng)求间螟,得到數(shù)據(jù)后臺(tái)再返還給前端吴旋。
2、代碼如下:
public static String getMsg(String url){//url為請(qǐng)求地址
try {
JSONObject param = new JSONObject();
//param.out("key","value")寒亥,添加請(qǐng)求的參數(shù)(body)
param.put("deviceSn", "0011613002A2");
param.put("fieldId", "66AA");
param.put("fieldValue", "1");
StringBuilder sb = new StringBuilder();
URL urlObj = new URL(url);
HttpURLConnection conn = (HttpURLConnection)urlObj.openConnection();
//post請(qǐng)求不能使用緩存
conn.setUseCaches(false);
// 設(shè)置是否向httpUrlConnection輸出邮府,因?yàn)檫@個(gè)是post請(qǐng)求,參數(shù)要放在http正文內(nèi)溉奕,因此????設(shè)為true, 默認(rèn)情況下是false;
conn.setDoOutput(true);
// 設(shè)置是否從httpUrlConnection讀入褂傀,默認(rèn)情況下是true;
conn.setDoInput(true);
// 設(shè)定請(qǐng)求的方法為"POST",默認(rèn)是GET
conn.setRequestMethod("POST");
//添加請(qǐng)求頭header
conn.setRequestProperty("token", "token");
conn.setRequestProperty("Content-Type", "application/json; charset=utf-8");
try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(conn.getOutputStream(),"UTF-8"))){
writer.write(param.toJSONString());
writer.flush();
}
try (BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(),"UTF-8"))){
String tmpLine;
while((tmpLine = reader.readLine()) != null){
sb.append(tmpLine);
}
}
conn.disconnect();
return sb.toString();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}
此方法示情況自己修改加勤,url請(qǐng)求地址仙辟,param請(qǐng)求參數(shù),conn.setRequestProperty請(qǐng)求頭鳄梅。返回結(jié)果為接口返回的字符串叠国。