【发布时间】:2016-05-03 06:53:19
【问题描述】:
下面的代码显示了一个方法,downloadUrl(),它接受一个字符串,“myurl”,它的参数。我曾经发送给它的只有两个可能的 url,并且每个方法的行为都不同。
当 myurl = URL1 时,它使用 GET 请求,一切正常。
然而,当myurl = URL2 时,它使用POST 请求,并且来自php 页面的响应表明随请求发送的post 参数为空。你可以看到我设置 POST 参数的那一行,所以我不明白为什么它没有发送任何参数?!
感谢您的帮助! -亚当。
private String downloadUrl(String myurl) throws IOException {
InputStream is = null;
String response = "";
try {
URL urlObject = new URL(myurl);
HttpURLConnection conn = (HttpURLConnection) urlObject.openConnection();
// find out if there's a way to incorporate these timeouts into the progress bar
// and what they mean for shitty network situations
conn.setReadTimeout(10000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setDoInput(true);
// INSERTED QUICK CHECK TO SEE WHICH URL WE ARE LOADING FROM
// it's important because one is GET, and one is POST
if (myurl.equals(url2)){
Log.i(TAG, "dlurl() in async recognizes we are doing pre-call");
conn.setRequestMethod("POST");
conn.setDoOutput(true);
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
String postParams = "?phone=" + phone;
writer.write(postParams);
Log.i(TAG, "we're adding " + postParams + "to " + urlObject);
writer.flush();
writer.close();
os.close();
}
else {
conn.setRequestMethod("GET");
conn.connect();
}
// Starts the query
int responseCode = conn.getResponseCode();
Log.i(TAG, "from " + myurl + ", The response code from SERVER is: " + responseCode);
is = conn.getInputStream();
// Convert the InputStream into a string
// i guess we look up how to do this
if (responseCode == HttpsURLConnection.HTTP_OK) {
String line;
BufferedReader br = new BufferedReader(new InputStreamReader(is));
while ((line = br.readLine()) != null) {
response += line;
}
} else {
response = "from downloadUrl, php page response was not OK: " + responseCode;
}
// it's good to close these things?
is.close();
conn.disconnect();
Log.i(TAG, "response is " + response);
return response;
// Makes sure that the InputStream is closed after the app is
// finished using it.
} finally {
if (is != null) {
is.close();
}
}
}
【问题讨论】:
-
你没有 conn.connect();在你的 if else 等于 url2
-
你的问题标题很有趣。专家需要 Android/Java。比如给个工作什么的!!!让它更清楚。
-
conn.connect() 不是问题……是的,对标题感到抱歉。哈哈。
标签: java android http post httpurlconnection