【发布时间】:2015-01-22 03:08:05
【问题描述】:
我通常使用 $.ajax 将我的应用程序数据发送到我的 WebService,如下所示:
$.ajax({
type: "POST",
url: server + "/fosco/set",
data: {
"page":"0",
"requestType":"DataSet",
"dataset":createClientJSONObject(),
"params":"[]"
},
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'User-Id' : localStorage.getItem("USER_ID")
},
success: SuccessSetData
现在,我为我的 Java 应用程序使用相同的 WebService,所以我想知道使用 HTTP POST 将其作为 Java 应用程序发送的等效代码。我开始了类似以下的操作,但不起作用:
String url = "http://localhost/service/index.php/fosco/set";
String returnBody = "";
Gson gson = new Gson();
Client fc = new Client();
try {
HttpRequest httpRequest = new HttpRequest();
Hashtable<String, String> params = new Hashtable<String, String>();
params.put("page", "0");
params.put("requestType", "DataSet");
params.put("dataset", gson.toJson(new Client()));
params.put("params", "[]");
returnBody = httpRequest.post(url,
params);
我已经调试了我的 PHP WebService,它显示了不同的数据集,它将 JAVA 应用程序数据集显示为一个完整的字符串,但将 $.ajax 显示为结构化的 JSON 对象。而且它不适用于 JAVA 代码。
问题: 如何将像我上面的 $.ajax POST 移植为 Java Http POST?
【问题讨论】:
-
Java版本中是否自动设置内容类型?
-
@Musa,嗯,标题上的内容类型和用户 ID 是在我的 HttpRequest 类中自动设置的。