通过 HTTP POST 发送参数和 Json
Sending params and Json via HTTP POST
我需要你的帮助来理解这件事。
我必须发出一个 http post 请求,然后我必须发送参数和一个非常大的 json 数组(data= [jsonarray])。
现在,如果我只需要发送参数没问题..但我不知道如何发送 jsonarray。
我如何实现一个部分来发送我的 json 数组?
提前致谢。
这是我的代码:
public static String post(String requestURL, HashMap<String, String> postDataParams, JSONArray jsonArray) {
URL url;
String response = "";
try {
url = new URL(requestURL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(TIMEOUT_CONNECTION);
conn.setConnectTimeout(TIMEOUT_CONNECTION);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
if (postDataParams != null) {
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(getPostDataString(postDataParams));
writer.flush();
writer.close();
os.close();
}
int responseCode = conn.getResponseCode();
if (responseCode == HttpsURLConnection.HTTP_OK) {
String line;
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
while ((line = br.readLine()) != null) {
response += line;
}
} else {
response = "";
}
} catch (Exception e) {
e.printStackTrace();
response = "";
String strParams = postDataParams != null ? postDataParams.toString() : "";
IMLog.e(TAG, "Error....");
}
return response;
}
使用 toString()
方法将您的 JSONArray 转换为字符串。之后你可以像任何其他参数一样将它添加到你的 HashMap 中。
String jsonArrayString = jsonArrayObject.toString();
其中,jsonArrayObject:
您的对象包含 JSONArray。
我需要你的帮助来理解这件事。 我必须发出一个 http post 请求,然后我必须发送参数和一个非常大的 json 数组(data= [jsonarray])。 现在,如果我只需要发送参数没问题..但我不知道如何发送 jsonarray。 我如何实现一个部分来发送我的 json 数组? 提前致谢。 这是我的代码:
public static String post(String requestURL, HashMap<String, String> postDataParams, JSONArray jsonArray) {
URL url;
String response = "";
try {
url = new URL(requestURL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(TIMEOUT_CONNECTION);
conn.setConnectTimeout(TIMEOUT_CONNECTION);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
if (postDataParams != null) {
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(getPostDataString(postDataParams));
writer.flush();
writer.close();
os.close();
}
int responseCode = conn.getResponseCode();
if (responseCode == HttpsURLConnection.HTTP_OK) {
String line;
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
while ((line = br.readLine()) != null) {
response += line;
}
} else {
response = "";
}
} catch (Exception e) {
e.printStackTrace();
response = "";
String strParams = postDataParams != null ? postDataParams.toString() : "";
IMLog.e(TAG, "Error....");
}
return response;
}
使用 toString()
方法将您的 JSONArray 转换为字符串。之后你可以像任何其他参数一样将它添加到你的 HashMap 中。
String jsonArrayString = jsonArrayObject.toString();
其中,jsonArrayObject:
您的对象包含 JSONArray。