http接口,报空指针,请教大虾
项目中要做一个发短信的功能,客户给了一个http接口url,一开始以为直接这样用BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); 后来那个开发接口的公司说不能这样使用,也不能直接在浏览器窗口中输入url的请求:因为他们后台是这么处理的:
String result = "";
request.setCharacterEncoding("GBK");
BufferedReader br = request.getReader();
String line = br.readLine();
String[] params = line.split("&");
Map<String,Object> param = new HashMap<String,Object>();
for(String s : params){
String[] keyAndValue = s.split("=");
String key = keyAndValue[0];
String value = keyAndValue[1];
if(key.equals("SMSContent") || key.equals("DestMobile")) {
value = URLDecoder.decode(value,"GBK");
}
param.put(key, value);
if(!isOpen)System.out.println(key+":"+value);
}
if(!isOpen)System.out.println("");
String BizType = param.get("BizType").toString();
if(BizType.equals("01")){
result = smsWordService.senMsgServiceAPI(param);
}else if(BizType.equals("02")){
System.out.println("已发短信查询");
}else if(BizType.equals("03")){
System.out.println("上行短信查询");
}
os.write(params.getBytes());
os.flush();
os.close();
connection.getResponseCode();
connection.disconnect();
[解决办法]
String inputParam = "BizType=01&LoginName=stjbpt&Password=st7023";
URL url = null;
HttpURLConnection httpConn = null;
OutputStream output = null;
OutputStreamWriter outr = null;
url = new URL("http://10.32.10.190/sms/SMSOutServlet");
//通过接口建立你的链接
httpConn = (HttpURLConnection) url.openConnection();
//这都不用你管了,都是些提交方式的写法,不过你最好确认一下是不是POST
HttpURLConnection.setFollowRedirects(true);
httpConn.setDoOutput(true);
httpConn.setRequestMethod("POST");
httpConn.setRequestProperty("Content-Type", "text/xml");
httpConn.connect();
//获取输出流
output = httpConn.getOutputStream();
//套接
outr = new OutputStreamWriter(output);
// 写入请求参数
outr.write(inputParam.toString().toCharArray(), 0, inputParam
.toString().length());
outr.flush();
outr.close();
这样穿过去是没啥问题的,但你说的为空我很在意是他们获取不到还是你获取不到呢