HttpURLConnection: java.lang.IllegalStateException: Already connected

前端 未结 3 870
隐瞒了意图╮
隐瞒了意图╮ 2021-02-20 09:17

I\'m trying to use HttpURLClient to send some POST data to a server using the HttpRestClient class shown below. When executing

conn.setDoInput(true)         


        
相关标签:
3条回答
  • 2021-02-20 09:29

    This might be due to watches while debugging in your IDE. See this answer. It happened to me and was hard to discover.

    0 讨论(0)
  • 2021-02-20 09:30

    It may be a misleading exception. See this defect for Jersey-2 https://java.net/jira/browse/JERSEY-2729

    The link has been updated: https://github.com/jersey/jersey/issues/3001

    Basically the issue is jersey was throwing invalid exception. The real issue in my case was that the connection was refused from the server.

    0 讨论(0)
  • 2021-02-20 09:48

    You called both of conn.setDoInput(true); and conn.setDoOutput(true);. Use one of them:

    • setDoOutput(true) is used for POST and PUT requests.
    • setDoInput(true) is used for GET request.

    The connection you made was confused, it can't decide which request should be used.

    In your code:

    static public int post(String urlStr, List<NameValuePair> data){
        HttpURLConnection conn = null;
        System.setProperty("http.keepAlive", "false"); // must be set
        try {
            ...
            conn.setDoOutput(true);
            conn.setRequestMethod("POST");
            // and connect to server, if needed
            conn.connect();
            ...
        }
    ....
    
    0 讨论(0)
提交回复
热议问题