我正在尝试使用参数将数据发布到url。 我需要发布一些数据字符串以及参数。
HttpURLConnection cnn = null;
InputStream strIn = null;
String ret = null;
try {
URL url = new URL("http://server.com?param1=1¶m2=2");
cnn = getConnection(url);
cnn.setConnectTimeout(_nTimeout);
cnn.setReadTimeout(_nTimeout);
cnn.setDoOutput(true);
cnn.setRequestMethod("POST");
cnn.setUseCaches(false);
cnn.setRequestProperty("Content-Type", "text/plain");
cnn.connect();
DataOutputStream strOut = new DataOutputStream(cnn.getOutputStream ());
strOut.write(myData.getBytes("UTF-8"));
strOut.flush();
strOut.close();
int status = cnn.getResponseCode();
if (status == 200){
strIn = cnn.getInputStream();
}
else {
strIn = cnn.getErrorStream();
}
BufferedReader rd = new BufferedReader(new InputStreamReader(strIn));
StringBuilder response = new StringBuilder();
String line;
while((line = rd.readLine()) != null) {
response.append(line);
response.append('\r');
}
ret = response.toString();
} catch (IOException e) {
e.printStackTrace();
throw e;
}
catch (Exception e) {
e.printStackTrace();
IOException exNew = new IOException("HTTP unknown exception", e.getCause());
throw exNew;
} finally {
if (strIn != null) {
Utility.close(strIn);
}
if (cnn != null) {
cnn.disconnect();
}
}
return ret;
似乎,我的参数被忽略了。 我必须知道应该将参数插入到帖子消息的正文中:
StringBuilder postData = new StringBuilder();
for (Map.Entry<String,Object> param : params.entrySet()) {
if (postData.length() != 0) postData.append('&');
postData.append(URLEncoder.encode(param.getKey(), "UTF-8"));
postData.append('=');
postData.append(URLEncoder.encode(String.valueOf(param.getValue()), "UTF-8"));
}
byte[] postDataBytes = postData.toString().getBytes("UTF-8");
cnn.getOutputStream().write(postDataBytes);
然后我的数据myData应放在哪里?