HTTPURLConnection Getoutputstream挂起

时间:2012-11-20 21:30:09

标签: java android post android-emulator

我正在编写一个java代码来向网址发送POST请求,但它正在以粗体表示的行上被绞死。我在Android模拟器上运行它

URL url = new URL("htt
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("POST");
OutputStream urlc = connection.getOutputStream(); //line on which code is getting hanged
OutputStreamWriter writer = new OutputStreamWriter(urlc);
writer.write("message");
writer.close();

我也可以在模拟器浏览器上运行互联网。那是我检查过互联网正在运作。

3 个答案:

答案 0 :(得分:1)

我有同样的问题,我的错误是我设置了太大的超时(120秒)。 更大的超时使HttpUrlConnection在消耗每一行之前等待更多时间。当我把它减少到20秒时,它的工作速度要快得多。

改变之前 - 等待时间4-5秒 改变后 - 只需0.5-1.5秒。

答案 1 :(得分:0)

请参阅this我的答案之一将帮助您并指导您正确的方向。

答案 2 :(得分:0)

我有同样的问题。您必须为应用程序启用计费。

如果未启用计费功能,则Java 8环境中的本机(HttpURLConnection)将不起作用。

https://cloud.google.com/appengine/docs/standard/java/issue-requests

  

当您的应用以默认行为在Java 8中运行时,您必须启用您的应用进行计费,否则您将获得以下例外情况:

     
      
  • java.net.UnknownHostException
  •   
  • java.net.SocketTimeoutException
  •   
  • java.io.IOException
  •   

另一种选择是使用旧式urlfetch,但是,您将遇到其他问题,例如:

Got "DatastoreException: Request is missing required authentication credential" if using Objectify 6.0 and <url-stream-handler> at the same time