所以我花了6个小时的时间来弄清这个“小”事实:
如果不调用client.getResponseCode(),则POST请求不会通过。

我希望有人能解释原因!
具体来说,对于此简约的android客户端独立代码,如果没有int status = client.getResponseCode();行,则什么也不会发生
但是有了它,一切都变得像魔术一样。
我没有找到任何与此有关的官方文档,所以我想知道最新消息或我不了解的东西(实施Java的人员通常做得很好,所以我可能没有得到什么:))。

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        final String theUrl = "http://xx.yyy.zz.aa:bb/securitiesFollowServer/users";
        final String TAG = getClass().getSimpleName();

        AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>() {
            @Override
            protected Void doInBackground(Void... params) {
                String body = "BODY OF MESSAGE";

                HttpURLConnection client = null;
                BufferedWriter outputPost = null;

                try {
                    URL url = new URL(theUrl);

                    //  open the connection
                    client = (HttpURLConnection) url.openConnection();
                    client.setRequestProperty("content-type", "text/plain");
                    //client.setRequestMethod("POST"); Someone claimed that setDoOutput(true) works so I will try that instead (I tried both,mutually and exclusively so all 3 options).
                    client.setDoOutput(true);

                    outputPost = new BufferedWriter(new OutputStreamWriter(client.getOutputStream()));
                    outputPost.write(body);
                    outputPost.flush();
                    outputPost.close();
                    int status = client.getResponseCode();
                    StackTraceElement[] r = Thread.currentThread().getStackTrace();
                    String toNotepad = "";
                    for (int i = 0; i < r.length; ++i) {
                        toNotepad += '\n' + String.valueOf(i) + '.' + ':' + r[i].toString();
                    }
                    // This is where I set a breakpoint and got the stacktrace value from toNotepad,and copy pasted it.
                } catch (IOException e) {
                    Log.e(TAG, "Error ", e);
                } finally {
                    if (client != null) {
                        client.disconnect();
                    }
                    if (outputPost != null) {
                        try {
                            outputPost.close();
                        } catch (IOException e) {
                            Log.e(TAG, "IO ERROR");
                        }
                    }

                    return null;
                }
            }
        };
        task.execute();
    }
}


为了完整起见,这里是“服务器端”的简约代码

@POST
@Consumes(MediaType.TEXT_PLAIN)
@Produces(MediaType.TEXT_PLAIN)
public String setDebugResource(String a){
    return "I got this string:"+a;}


这是stacktrace(在上面的代码中我明确地复制粘贴了它的值,这很明显):

当不工作(或工作时,它是完全相同的堆栈跟踪):

0.:dalvik.system.VMStack.getThreadStackTrace(Native Method)
1.:java.lang.Thread.getStackTrace(Thread.java:580)
2.:dor.only.dorking.android.apppostrequest.MainActivity$1.doInBackground(MainActivity.java:52)
3.:dor.only.dorking.android.apppostrequest.MainActivity$1.doInBackground(MainActivity.java:28)
4.:android.os.AsyncTask$2.call(AsyncTask.java:292)
5.:java.util.concurrent.FutureTask.run(FutureTask.java:237)
6.:android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
7.:java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
8.:java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
9.:java.lang.Thread.run(Thread.java:818)

最佳答案

根据HttpUrlConnection docs,您必须在客户端对象上调用setDoOutput(true),而不是将方法设置为POST。通过该方法,该方法将自动设置为POST。他们在“发布内容”部分下有一个示例。

还有一个示例here和更大的讨论here

坦白说,我会跳过使用原始的HttpUrlConnection类,而使用诸如Volley之类的东西。

10-05 21:14
查看更多