Android Put Method错误

时间:2018-05-04 10:13:19

标签: java android put

我尝试使用PUT方法向服务器发送消息,但它不起作用。你能解决这个问题:java.net.ProtocolException: java cannot write request body after response has been read o

class DoUpdateSlides extends AsyncTask<String, Void, Void> {
    @Override
    protected Void doInBackground(String... params) {
        String JSONData = params[0];

        try {
            URL url = new URL(API);
            HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
            httpURLConnection.setRequestMethod("PUT");

            httpURLConnection.setDoOutput(true);
            httpURLConnection.connect();
            int statusCode = httpURLConnection.getResponseCode();
            System.out.println(statusCode);

            OutputStream dos =  httpURLConnection.getOutputStream();
            dos.write(JSONData.getBytes());

            InputStream is = httpURLConnection.getInputStream();
            String result = "";
            int byteCharacter;
            while ((byteCharacter = is.read())!=-1){
                result += (char)byteCharacter;
            }
            Log.d("json api","DoUpdateSlides.doInBackground Json return: "+ result);


        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }
}

堆栈跟踪:

System.err: java.net.ProtocolException: cannot write request body after 
       response has been read
05-04 17:20:26.753 5631-5645/com.aden.vidit.learningcrud 
W/System.err: at com.android.okhttp.internal.http.HttpURLConnectionImpl.getOutputStream(HttpURLConnectionImpl.java:203)
        at com.aden.vidit.learningcrud.EditActivity$DoUpdateSlides.doInBackground(EditActivity.java:137)
        at com.aden.vidit.learningcrud.EditActivity$DoUpdateSlides.doInBackground(EditActivity.java:121)
        at android.os.AsyncTask$2.call(AsyncTask.java:288)
        at java.util.concurrent.FutureTask.run(FutureTask.java:237)
        at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
        at java.lang.Thread.run(Thread.java:841)

1 个答案:

答案 0 :(得分:1)

HTTP协议基于请求 - 响应模式。您首先发送请求,服务器响应。一旦服务器响应,您就无法发送更多内容,这是没有意义的。

当您致电getResponseCode()时,您有效地告诉服务器您的请求已完成并且可以处理它。如果要发送更多数据,则必须开始新请求。

在致电getResponseCode()

之前移动此代码
OutputStream dos =  httpURLConnection.getOutputStream();
dos.write(JSONData.getBytes());

完成后应关闭连接(使用try并catch并关闭finally块中的连接)。