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

时间:2016-01-06 10:55:21

标签: 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)

1 个答案:

答案 0 :(得分:0)

通过添加

解决了我的问题
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;
}