使用httpUrlConnection:我正确设置了我的连接吗?

时间:2015-11-10 21:41:46

标签: java android http httpurlconnection urlconnection

我正在使用HttURLconnectionURLConnection api连接到我的网络主机(x10host)上的PHP文件。但是,似乎没有建立连接,也没有发送字符串数据。

我确信我的PHP代码是正确的,所以我在下面的代码中错误地使用了这些类吗?

@Override
            protected String doInBackground(String... params) {

                StringBuilder respData = new StringBuilder();
                InputStream stream = null;
                OutputStream os = null;
                HttpURLConnection httpUrlConnection;
                URLConnection conn;
                URL url;

                try {

                    url = new URL("my_url/recieveString.php");
                    conn = url.openConnection();
                    httpUrlConnection = (HttpURLConnection) conn;

                    httpUrlConnection.setUseCaches(false);
                    //httpUrlConnection.setRequestProperty("User-Agent", "App");
                    httpUrlConnection.setConnectTimeout(30000);
                    httpUrlConnection.setReadTimeout(30000);
                    httpUrlConnection.setRequestMethod("POST");
                    httpUrlConnection.setDoOutput(true);
                    os = httpUrlConnection.getOutputStream();

                    toSubmit = "test";

                    stream = new ByteArrayInputStream(toSubmit.getBytes(StandardCharsets.UTF_8));

                    copy(stream, os);

                    httpUrlConnection.connect();

                    int responseCode = httpUrlConnection.getResponseCode();

                    if (200 == responseCode) {
                        InputStream is = httpUrlConnection.getInputStream();
                        InputStreamReader isr = null;
                        try {
                            isr = new InputStreamReader(is);
                            char[] buffer = new char[1024];
                            int len;
                            while ((len = isr.read(buffer)) != -1) {
                                respData.append(buffer, 0, len);
                            }
                        } finally {
                            if (isr != null) {
                                isr.close();
                                success = true;
                            }
                        }
                        is.close();
                    } else {
                        // use below to get error stream
                        //inputStream = httpUrlConnection.getErrorStream();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    try {
                        stream.close();
                        os.flush();

                        os.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }

                    return "done";
                }
            }

0 个答案:

没有答案