对方定义的Web接口,接收JSON对象,返回也是JSON对象。
在编码过程中遇到了一点小问题,以下是完整代码。
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import net.sf.json.JSONObject;
public class HttpPost {
private JSONObject Send(String urlStr, JSONObject jObj) throws IOException {
String retValue = null;
URL url = new URL(urlStr);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
// 以Post方式发送
con.setRequestMethod("POST");
con.setDoInput(true);
con.setDoOutput(true);
// 设置内容类型为文本或者html
con.setRequestProperty("Content-type", "text/html");
PrintWriter out = new PrintWriter(con.getOutputStream());
// 对方接口要求带[]符号
out.println("[" + jObj.toString() + "]");
out.flush();
out.close();
BufferedReader l_reader = new BufferedReader(new InputStreamReader(
con.getInputStream()));
StringBuffer buff = new StringBuffer();
String line;
while ((line = l_reader.readLine()) != null) {
buff.append(line + "\n");
}
l_reader.close();
con.disconnect();
retValue = buff.toString();
if (retValue.length() > 2) {
retValue = retValue.substring(1, retValue.length() - 2);
return JSONObject.fromObject(retValue);
} else
return null;
}
public static void main(String[] args) throws IOException {
HttpPost hp = new HttpPost();
JSONObject jUser = new JSONObject();
jUser.put("userName", "njupt");
JSONObject jUserAcs = new JSONObject();
jUserAcs.put("UserAccess", jUser);
System.out
.println(hp
.Send("http://ip:port/smartHome/mobile/UserAccess.action",
jUserAcs));
}
}
JSON用到的jar包可以从这里下载:http://134.iteye.com/blog/231782
推荐一个http抓包工具HTTP Analyzer:http://www.ieinspector.com/httpanalyzer/download.html
用它来分析发送和接收的内容,之前一直调试不通过,因为request的contenttype不是text/html,是使用该抓包工具发现的。
以上
wuxiaochao@live.com