POST请求的有趣问题(HttpURLConnection) - 但为什么会发生?

时间:2016-05-25 10:21:53

标签: java android rest http post

所以我只花了6个小时的工作,弄清楚这个'小'事实: 不调用client.getResponseCode()后请求不会通过。

我希望有人可以解释原因! 具体来说,对于这个简约的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;}

这是堆栈跟踪(我在上面的代码中明显地将其复制粘贴了它的值):

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

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)

1 个答案:

答案 0 :(得分:1)

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

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

坦率地说,我会跳过使用原始的HttpUrlConnection类并使用像Volley这样的东西。