簡體   English   中英

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

[英]method does not support a request body: GET/POST

無法將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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM