我正在尝试在我的 android 应用程序中将一些数据发布到 https url,以获得 json 格式的响应。
我面临两个问题:
is = conn.getInputStream();
投掷
java.io.FileNotFoundException
如果我对 HttpsURLConnection 做错了什么,我不明白。
当我调试代码时出现第二个问题(使用 eclipse);我在之后设置了一个断点
conn.setDoOutput(true);
并且,在检查conn
值时,我看到变量doOutput
仍然设置为false
并键入GET
。
我的 https POST 方法如下,POSTData
扩展类在哪里ArrayList<NameValuePair>
private static String httpsPOST(String urlString, POSTData postData, List<HttpCookie> cookies) {
String result = null;
HttpsURLConnection conn = null;
OutputStream os = null;
InputStream is = null;
try {
URL url = new URL(urlString);
conn = (HttpsURLConnection) url.openConnection();
conn.setReadTimeout(10000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("POST");
conn.setUseCaches (false);
conn.setDoInput(true);
conn.setDoOutput(true);
if(cookies != null)
conn.setRequestProperty("Cookie",
TextUtils.join(";", cookies));
os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(postData.getPostData());
writer.flush();
writer.close();
is = conn.getInputStream();
BufferedReader r = new BufferedReader(
new InputStreamReader(is));
StringBuilder total = new StringBuilder();
String line;
while ((line = r.readLine()) != null) {
total.append(line);
}
result = total.toString();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (os != null) {
try {
os.close();
} catch (IOException e) {
}
}
if (is != null) {
try {
is.close();
} catch (IOException e) {
}
}
if (conn != null) {
conn.disconnect();
}
}
return result;
}
一点更新:显然 eclipse debug 对我撒谎,在 netbeans 上运行和调试显示POST
连接。错误似乎与我传递给 url 的参数有关。