Resolution of HttpURLConnection getInputStream anomalies

Source: Internet
Author: User

http://blog.csdn.net/q2232/article/details/48136973

Because read a lot of csdn articles, also did not find the corresponding solution, so the recently encountered a problem to write, to the future of the partners who encounter problems to provide some help.

In fact the problem is very simple, is very normal httpurlconnection post connection, when Getresponsecode for HTTPURLCONNECTION.HTTP_OK (200) and HTTPURLCONNECTION.HTTP_ CREATED (201) did not have any problems.

But when Getresponsecode is a custom value, such as 422, HttpURLConnection. getInputStream () reported abnormal,Java.io.FileNotFoundException:

Found many articles, some let comments off Httpurlconnection.setdooutput (true); This statement does not know how to come, Super pit Ah, we do not believe.

It is also said that judging Getresponsecode, not 200 will not go to getInputStream (), but the return value is my custom, return the content, must be obtained.

Finally look at the HttpURLConnection API documentation to discover the problem.

API Link: http://www.apihome.cn/api/java/HttpURLConnection.html

InputStream getErrorStream()
If the connection fails but the server still sends useful data, the error stream is returned.

Yes, that's him, Judge Getresponsecode, when the return is not HTTPURLCONNECTION.HTTP_OK, httpurlconnection.http_created, HttpURLConnection.HTTP_ACCEPTED 时,不能用getInputStream(),而是应该用getErrorStream()。修改代码,问题解决。


对于java开发,我们很多情况都是找实例,搜问题。确很少看API,其实API真的很重要。以后用不太熟悉的类时,一定要先看API,先看API先看API!

Resolution of HttpURLConnection getInputStream anomalies

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.