开发者社区> 问答> 正文

HttpURLConnection连接服务端 conn.getResponseC?报错

使用HttpURLConnnection连接服务端,老是报错405怎么回事,其他方法调用就没事。


private String toRegist(String phone,String phoneCode,String password) {
        HttpURLConnection conn = null;
        PrintWriter printWriter = null;  
        BufferedReader bufferedReader = null;
        StringBuffer responseResult = new StringBuffer();  
 try {
        String newUrl = URL +"?phone="+ phone + "&phoneCode=" + phoneCode + "&password=" + password;
        URL url = new URL(newUrl);
        conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("POST");// 提交模式
        conn.setRequestProperty("Content-Type", "plain/text; charset=UTF-8");  
        
        // 设置通用的请求属性  
            conn.setRequestProperty("accept", "*/*");  
            conn.setRequestProperty("connection", "Keep-Alive");  
            // 发送POST请求必须设置如下两行  
            conn.setDoOutput(true);  
            conn.setDoInput(true);
            conn.connect();
            // 根据ResponseCode判断连接是否成功  
            int responseCode = conn.getResponseCode();  
            if (responseCode != 200) {  
            	System.out.println("Not Success");
            } else {  
            	System.out.println("Success");
            }  
            // 定义BufferedReader输入流来读取URL的ResponseData  
            bufferedReader = new BufferedReader(new InputStreamReader(  
                    conn.getInputStream()));  
            String line;  
            while ((line = bufferedReader.readLine()) != null) {  
                responseResult.append(line);  
            }  
 /* 关闭DataOutputStream */
 } catch (IOException e) {
 e.printStackTrace();
 } catch (Exception e) {
 e.printStackTrace();
 }finally{
 conn.disconnect();  
            try {  
                if (printWriter != null) {  
                    printWriter.close();  
                }  
                if (bufferedReader != null) {  
                    bufferedReader.close();  
                }  
            } catch (IOException ex) {  
                ex.printStackTrace();  
            } 
 }
 return responseResult.toString();
 }

参数是我自己拼上的,到底是哪里的错误,纠结万分。


展开
收起
爱吃鱼的程序员 2020-06-12 11:15:18 616 0
1 条回答
写回答
取消 提交回答
  • https://developer.aliyun.com/profile/5yerqm5bn5yqg?spm=a2c6h.12873639.0.0.6eae304abcjaIB

    405说明你请求方法不对,从你的URL上来看,这个请求应该是GET才对。

    405MethodNotAllowed

    ThemethodspecifiedintheRequest-LineisnotallowedfortheresourceidentifiedbytheRequest-URI.TheresponseMUSTincludeanAllowheadercontainingalistofvalidmethodsfortherequestedresource.


    引用来自“狐狸糊涂”的评论

    405说明你请求方法不对,从你的URL上来看,这个请求应该是GET才对。

    405MethodNotAllowed

    ThemethodspecifiedintheRequest-LineisnotallowedfortheresourceidentifiedbytheRequest-URI.TheresponseMUSTincludeanAllowheadercontainingalistofvalidmethodsfortherequestedresource.


    2020-06-12 11:15:35
    赞同 展开评论 打赏
问答分类:
问答地址:
问答排行榜
最热
最新

相关电子书

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