我正在开发一个需要与服务器连接的Android应用程序。为了测试我的HTTP帖子是否有效,我使用的是posttestserver.com。唉,虽然收到我发送的邮件,但我收不到我试图发送的邮政参数。我在我的Manifest中启用了互联网许可(我在其他问题中看到了很多东西)但是,我仍然无法获得数据。我的代码是:
public String uploadData(String dataLine) throws MalformedURLException {
URL url = new URL(urlName);
HttpURLConnection urlConnection;
String text = "";
BufferedReader reader = null;
try {
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setDoOutput(true);
urlConnection.setDoInput(true);
urlConnection.setChunkedStreamingMode(0);
urlConnection.setRequestMethod("POST");
urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
Uri.Builder builder = new Uri.Builder()
.appendQueryParameter("key", key)
.appendQueryParameter("data", dataLine);
String query = builder.build().getEncodedQuery();
OutputStream os = urlConnection.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(query);
writer.flush();
writer.close();
os.close();
urlConnection.connect();
reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
// Read Server Response
while((line = reader.readLine()) != null)
{
// Append server response in string
sb.append(line + "\n");
}
reader.close();
text = sb.toString();
} catch (IOException e) {
e.printStackTrace();
}
return text;
}
我最初用
之类的东西构建Post数据String POST = "key="+URLEncoder.encode(key, "UTF-8");
但在另一个帖子中,我看到了这个方法。 (How to add parameters to HttpURLConnection using POST)
http://posttestserver.com/data/2015/07/27/14.39.441876894412这是一个没有带参数的POST请求。