开发者社区> 问答> 正文

HttpURLConnection Already connected异常 400 请求报错 

小白又来提问题了,多方寻求无解 
正在做上传使用的是HttpURLConnection加sessionID上传用户数据
昨天上传还很正常,下午快下班了就报错,老夫心痛 T_T
上传代码如下:

public static void upload(String host,String sessionID,File file,Map<String,String> params,FileUploadListener listener){

    String BOUNDARY = UUID.randomUUID().toString(); //边界标识 随机生成 String PREFIX = "--" , LINE_END = "\r\n";
    String CONTENT_TYPE = "multipart/form-data"; //内容类型
    HttpURLConnection conn=null;
    //System.setProperty("http.keepAlive", "false");
    //System.setProperty("sun.net.http.allowRestrictedHeaders", "true");
    try {
        URL url = new URL(host);
        conn = (HttpURLConnection) url.openConnection();

        conn.setReadTimeout(TIME_OUT);
        conn.setConnectTimeout(TIME_OUT);
        conn.setRequestMethod("POST"); //请求方式
        conn.setRequestProperty("cookie",sessionID);
        conn.setRequestProperty("Charset", "utf-8");//设置编码
        conn.setRequestProperty("connection", "keep-alive");
        conn.setRequestProperty("Content-Type", CONTENT_TYPE + ";boundary=" + BOUNDARY);
        //conn.setDoInput(true); //允许输入流
        conn.setDoOutput(true); //允许输出流
        conn.setUseCaches(false); //不允许使用缓存

        if(file!=null) {
            /** * 当文件不为空,把文件包装并且上传 */
            OutputStream outputSteam=conn.getOutputStream();
            try {
                DataOutputStream dos = new DataOutputStream(outputSteam);
                conn.setChunkedStreamingMode(1024*100);
                StringBuffer sb = new StringBuffer();
                sb.append(LINE_END);

                if(params!=null){//根据格式,开始拼接文本参数
                    for(Map.Entry<String,String> entry:params.entrySet()){
                        sb.append(PREFIX).append(BOUNDARY).append(LINE_END);//分界符
                        sb.append("Content-Disposition: form-data; name=\"" + entry.getKey() + "\"" + LINE_END);
                        sb.append("Content-Type: text/plain; charset=" + CHARSET + LINE_END);
                        sb.append("Content-Transfer-Encoding: 8bit" + LINE_END);
                        sb.append(LINE_END);
                        sb.append(entry.getValue());
                        sb.append(LINE_END);//换行!
                    }
                }
                sb.append(PREFIX);//开始拼接文件参数
                sb.append(BOUNDARY); sb.append(LINE_END);

                sb.append("Content-Disposition: form-data; name=\"coverpic\"; filename=\""+file.getName()+"\""+LINE_END);
                sb.append(LINE_END);
                //写入文件数据
                dos.write(sb.toString().getBytes());
                InputStream is = new FileInputStream(file);
                byte[] bytes = new byte[1024];
                long totalbytes = file.length();
                long curbytes = 0;
                Log.i("cky", "total=" + totalbytes);
                int len = 0;
                while((len=is.read(bytes))!=-1){
                    curbytes += len;
                    dos.write(bytes, 0, len);
                    listener.onProgress(curbytes, 1.0d * curbytes / totalbytes);
                }
                is.close();
                dos.write(LINE_END.getBytes());//一定还有换行
                byte[] end_data = (PREFIX+BOUNDARY+PREFIX+LINE_END).getBytes();
                dos.write(end_data);
                dos.flush();
                /**
                 * 获取响应码 200=成功
                 * 当响应成功,获取响应的流
                 */
                int code = conn.getResponseCode();

                if (code == 200) {
                    InputStream iss = conn.getInputStream();
                    String state = getStringFromISS(iss);
                    listener.onFinish(state);
                }
            }catch (Exception e) {
                Log.e("test", "捕获异常 " + e.getMessage() + " | " + e.getLocalizedMessage());
            }

        }
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }finally {
        if (conn != null) conn.disconnect();
    }

}</pre> 

在debug的时候显示:

参考 
http://stackoverflow.com/questions/23738940/httpurlconnection-java-lang-illegalstateexception-already-connected

展开
收起
kun坤 2020-05-28 16:05:57 1834 0
1 条回答
写回答
取消 提交回答
  • 引用来自“罪恶的花生”的评论

    为什么不考虑httpclient 用的sdk 23.0.2 , HttpClient被移除了###### ######为什么不考虑httpclient
    2020-05-29 13:09:07
    赞同 展开评论 打赏
问答地址:
问答排行榜
最热
最新

相关电子书

更多
低代码开发师(初级)实战教程 立即下载
冬季实战营第三期:MySQL数据库进阶实战 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载