0

我正在尝试在我的 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 的参数有关。

4

1 回答 1

1

FileNotFoundException表示您发布到的 URL 不存在,或者无法映射到 servlet。它是 HTTP 404 状态代码的结果。

如果调试器与程序的行为方式不一致,请不要担心您在调试器中看到的内容。如果doOutput真的没有启用,你会得到一个获取输出流的异常。

于 2014-02-10T23:39:44.850 回答