简体   繁体   English

带有标题信息但没有正文的HttpUrlConnection Post

[英]HttpUrlConnection Post with header info but no body

I am developing an Android app that uses an API I developed. 我正在开发使用我开发的API的Android应用。

I am doing this connection using HttpUrlConnection and so far the login works fine. 我正在使用HttpUrlConnection进行此连接,到目前为止登录工作正常。 The problem arises with the logout. 问题出自注销。 It´s not doing anything. 它什么也没做。 When I do the logout request with Postman then it works fine, but with HttpUrlConnection it does not. 当我用Postman执行注销请求时,它可以正常工作,但使用HttpUrlConnection时,它却不能。

The logout works like this: Do a POST request to http://ipaddress:12345/api/LogOut 注销的工作方式如下:向http:// ipaddress:12345 / api / LogOut发出POST请求

and in the header include the token of the logged user. 并在标题中包含已登录用户的令牌。 Then the server should go to the database and delete the token for that user: 然后,服务器应转到数据库并删除该用户的令牌:

This is how I´m trying to do the request: 这就是我尝试执行的请求:

URL url = new URL(getString(R.string.url) + "LogOut");
HttpURLConnection con = (HttpURLConnection) url.openConnection();

con.setRequestProperty("Content-Type", "application/json");
con.setRequestProperty("Token", TokenSingleton.getToken());

con.setReadTimeout(10000);
con.setConnectTimeout(15000);
con.setRequestMethod("POST");
con.setDoInput(true);
con.setDoOutput(true);
con.setUseCaches(false);

con.connect();
con.getOutputStream().flush();
con.getOutputStream().close();
con.disconnect();

Nothing happens until you do some input. 在您进行一些输入之前,什么都不会发生。 At least call getResponseCode() to see whether you got a 200 or not. 至少调用getResponseCode()来查看是否有200。 Preferably you should consume the input stream, if 200 <= response code <= 299, otherwise the error stream. 如果200 <=响应代码<= 299,则最好使用输入流,否则应使用错误流。

NB setDoOutput(true) sets the request method to POST. 注意: setDoOutput(true)将请求方法设置为POST。 You don't need to do that yourself. 您不需要自己做。 And setDoInput(true) is the default. setDoInput(true)是默认值。 And close() implies flush() . close()意味着flush()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM