Android对网站发表评论

时间:2016-10-08 06:06:52

标签: android

我试图在网站上发表评论,POST似乎没有给出错误,但似乎没有发挥作用。我不确定我哪里出错了?我是在一个单独的线程中调用它

    Thread thread = new Thread(new Runnable() {
        @Override
        public void run() {
            HttpURLConnection conn = null;
            try {
                String urlString = mainUrl +"?name=" + name;
                URL url = new URL(urlString);

                conn = (HttpURLConnection) url.openConnection();
                conn.setRequestMethod("POST");
                conn.setDoOutput(true);
                conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                conn.getOutputStream().write(comment.getBytes("UTF8"));
                conn.connect();

                int responseCode = conn.getResponseCode();
                Log.d("Response Code: ", "" + responseCode);


            } catch (Exception e) {
                Log.e("POST ERROR", e.toString());
            }
            finally {
                if (conn != null) {
                    conn.disconnect();
                }
            }
        }
    });
    thread.start();

1 个答案:

答案 0 :(得分:0)

试试这个:

    try {
            String urlString = mainUrl +"?name=" + name;
            url = new URL(urlString);
            urlConnection =(HttpURLConnection) url.openConnection();
            urlConnection.setRequestProperty("Content-Type", "application/json");
            urlConnection.setRequestMethod("POST");
            urlConnection.setDoInput(true);
            urlConnection.setDoOutput(true);
            urlConnection.connect();
            setupDataToDB();
            outputStreamWriter = new OutputStreamWriter(urlConnection.getOutputStream());
            outputStreamWriter.write(dataToWrite.toString());
            Log.e("Data To Write", dataToWrite.toString());

            outputStreamWriter.flush();
            outputStreamWriter.close();
            int responseCode = urlConnection.getResponseCode();
            Log.e("Response Code ", String.valueOf(responseCode));
            if (responseCode == 404){
                Log.e("Status Code", "404");
            }else if (responseCode == 200){
                Log.e("Status Code", "200");
        } catch (Exception e) {
            urlConnection.getErrorStream();
            e.printStackTrace();
        }

    private void setupDataToDB() {
        dataToWrite = new JSONObject();
        try {
            dataToWrite.put("comment", comment);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

并且不要忘记将它们声明为全局变量:

private HttpURLConnection urlConnection;
private URL url;
private OutputStreamWriter outputStreamWriter;
private JSONObject dataToWrite;

希望它有所帮助!!!