java - 方法不支持请求正文: GET/POST

标签 java android http http-post httprequest

无法向服务器发送 GET 或 POST 回复请求,出现以下错误

java.net.ProtocolException: method does not support a request body: GET/POST

我尝试做的是阅读网站内容并计算其中生成的简单数学方程并将答案发送回服务器。无法弄清楚为什么它会抛出异常以及如何解决我的问题。

class HTTPRequest extends AsyncTask<String, String, String> {
    String field1;
    String field2;

    public HTTPRequest (String arg1, String arg2) {
        field1 = arg1;
        field2 = arg2;
    }

    @Override
    protected String doInBackground(String... urls) {
        try {
            URL url = new URL(urls[0]);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setDoOutput(true);
            conn.setChunkedStreamingMode(0);

            InputStream in = new BufferedInputStream(conn.getInputStream());
            String html = readStream(in);

            Pattern pattern = Pattern.compile("\\t+(\\d+) ([+-]) (\\d+) = <input name=\"answer\"");
            Matcher matcher = pattern.matcher(html);

            Integer res = null;
            if (matcher.find()) {
                if (matcher.group(2).equals("-"))
                    res = Integer.parseInt(matcher.group(1)) - Integer.parseInt(matcher.group(3));
                else if (matcher.group(2).equals("+"))
                    res = Integer.parseInt(matcher.group(1)) + Integer.parseInt(matcher.group(3));
            }

            //Result is calculated! sending POST request
            if (res != null) {
                Log.d("RESULT", Integer.toString(res));
                String data = URLEncoder.encode("field1", "UTF-8")
                        + "=" + URLEncoder.encode(field1, "UTF-8");
                data += "&" + URLEncoder.encode("field2", "UTF-8") + "="
                        + URLEncoder.encode(field2, "UTF-8");
                data += "&" + URLEncoder.encode("answer", "UTF-8") + "="
                        + URLEncoder.encode(Integer.toString(res), "UTF-8");

                //ERR ON THIS LINE
                DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
                wr.writeBytes(data);
                wr.flush();
                wr.close();

                BufferedReader in1 = new BufferedReader(
                        new InputStreamReader(conn.getInputStream()));
                String inputLine;
                StringBuffer response = new StringBuffer();

                while ((inputLine = in1.readLine()) != null) {
                    response.append(inputLine);
                }
                in.close();
                Log.d("RESPONE",respone);

            }
            conn.disconnect();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    private String readStream(InputStream is) throws IOException {
        StringBuilder sb = new StringBuilder();
        BufferedReader r = new BufferedReader(new InputStreamReader(is),1000);
        for (String line = r.readLine(); line != null; line =r.readLine()){
            sb.append(line);
            sb.append(System.getProperty("line.separator"));
        }
        is.close();
        return sb.toString();
    }
}

回溯:

System.err: java.net.ProtocolException: method does not support a request body: POST
System.err:     at libcore.net.http.HttpURLConnectionImpl.getOutputStream(HttpURLConnectionImpl.java:201)
System.err:     at com.streak.myapp.HTTPRequest.doInBackground(HTTPRequest.java:73)
System.err:     at com.streak.myapp.HTTPRequest.doInBackground(HTTPRequest.java:24)
System.err:     at android.os.AsyncTask$2.call(AsyncTask.java:287)
System.err:     at java.util.concurrent.FutureTask.run(FutureTask.java:234)
System.err:     at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
System.err:     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
System.err:     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
System.err:     at java.lang.Thread.run(Thread.java:841)

最佳答案

通过添加解决了我的问题

CookieHandler.setDefault( new CookieManager( null, CookiePolicy.ACCEPT_ALL ) ); 

并创建与同一主机的新连接。

@Override
protected Void doInBackground(String... urls) {
    CookieHandler.setDefault( new CookieManager( null, CookiePolicy.ACCEPT_ALL ) );
    String data="";
    try {
        URL url = new URL(urls[0]);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();

        InputStream in = new BufferedInputStream(conn.getInputStream());
        String html = readStream(in);

        Pattern pattern = Pattern.compile("\\t+(\\d+) ([+-]) (\\d+) = <input name=\"answer\"");
        Matcher matcher = pattern.matcher(html);

        Integer res = null;
        if (matcher.find()) {
            if (matcher.group(2).equals("-"))
                res = Integer.parseInt(matcher.group(1)) - Integer.parseInt(matcher.group(3));
            else if (matcher.group(2).equals("+"))
                res = Integer.parseInt(matcher.group(1)) + Integer.parseInt(matcher.group(3));
        }

        if (res != null) {
            data += URLEncoder.encode("field1", "UTF-8")
                    + "=" + URLEncoder.encode(field1, "UTF-8");
            data += "&" + URLEncoder.encode("field2", "UTF-8") + "="
                    + URLEncoder.encode(field2, "UTF-8");
            data += "&" + URLEncoder.encode("answer", "UTF-8") + "="
                    + URLEncoder.encode(Integer.toString(res), "UTF-8");
        }
        conn.disconnect();
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    try {
        URL url = new URL(urls[0]);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        conn.setRequestProperty("charset", "utf-8");
        conn.setDoOutput(true); //ENABLE POST REQUEST
        DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
        wr.writeBytes(data);
        wr.flush(); wr.close();
        InputStream in = new BufferedInputStream(conn.getInputStream());
        data = readStream(in);
        conn.disconnect();
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    // Now data==final html respond
    Document doc = Jsoup.parse(data);
    Elements allAnchorTags = doc.select("tr");
    return null;
}

关于java - 方法不支持请求正文: GET/POST,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34631373/

相关文章:

java.lang.IllegalStateException : No parser found for urn:security:1. 1

java - 使用时从随机中删除数组

java - Android 应用程序在 Lollipop 上崩溃

http - 如何在仅显示 jpeg 时指定图标

apache - 发送 HTTP 1.0 请求以避免处理 block

java - 如何比较两个位置

java - 从 JSON 数组字符串创建 POJO 对象

所选项目的 Android 选择器不起作用

android - 捕获从Android设备播放的音频

json - 未进行 SSL 连接尝试时,MongoDB 提示 SSL 握手