不使用getResponse()无法发帖请求

时间:2016-05-31 12:47:37

标签: android httpurlconnection response-time

我使用HttpURLConnection在Azure服务器上发布。只有当我想从服务器返回响应代码时,请求才会成功。

private void PostStateSync(ProxyState mData) throws Exception
{
    GsonBuilder gsonBuilder= new GsonBuilder();
    gsonBuilder.serializeNulls();
    String json = gsonBuilder.create().toJson(mData);

    HttpURLConnection connection = null;
    URL object = new URL(ComURL);
    connection = (HttpURLConnection) object.openConnection();

    connection.setChunkedStreamingMode(0);

    connection.setReadTimeout(15000);
    connection.setConnectTimeout(15000);
    connection.setDoOutput(true);
    connection.setDoInput(true);
    connection.setRequestMethod("POST");
    connection.setRequestProperty("Content-Type", "application/json");
    connection.setRequestProperty("Accept", "*/*");
    connection.setRequestProperty("Accept-Encoding", "gzip, deflate");

    OutputStream os = connection.getOutputStream();
    BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
    bufferedWriter.write(json);
    bufferedWriter.flush();
    bufferedWriter.close();
    connection.connect();

    connection.getResponseCode();
    Log.v("Response state",String.valueOf(mStatus));

    Log.v("Response state","send");
}

在这种情况下请求有效但我有延迟问题导致服务器性能低下。为了改善请求时间,我尝试发表评论connection.getResponseCode();

如果我发表评论:

  

connection.getResponseCode();           Log.v("响应状态",String.valueOf(mStatus));

发布请求不起作用(我没有收到任何错误或在logcat中发出警告)。

这是我提出请求的线程。 (我在proxystatelist中每15秒收到一次数据)。我错过了什么?

    private void StartSendState()
{
    SendStateWorkerThread = new Thread(new Runnable() {
        @Override
        public void run() {
            while (canSendRun)
            {
                try {
                ProxyState proxyState;
                synchronized (proxyStateList) {
                    proxyState = proxyStateList.peek();
                }
                if (proxyState!=null) {
                    PostStateSync(proxyState);
                }
                    synchronized (proxyStateList)
                    {
                  proxyStateList.poll();
                }
                    Thread.sleep(5000);
                }
                catch (InterruptedException e) {
                    e.printStackTrace();
                }
                catch (Exception e) {
                e.printStackTrace();
                }
            }
        }
    });
    SendStateWorkerThread.start();
}

0 个答案:

没有答案