NutzCN Logo
问答 使用UrlConnection发送post请求,在main方法里正常,在nutz的某个action里就报异常
发布于 2546天前 作者 qq_99c1b36f 1773 次浏览 复制 上一个帖子 下一个帖子
标签:

五一。。。加班中。。

我想发送一个post请求,网上百度的。我写了一个util工具类,然后在里面写了main方法测试这个util,很正常。

但是,当我在nutz的某个action里,使用这个util时,在util里,conn.getInputStream();这句总是报io异常,新手,非常懵逼又着急。。。猜测是不是线程问题,
应该如何解决啊?【下面附上util代码】

/**
     * 向指定 URL 发送POST方法的请求
     * 
     * @param url
     *            发送请求的 URL
     * @param param
     *            请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
     * @return 所代表远程资源的响应结果
     */
    public static String sendPost(String url, String param) {
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            // 设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("Content-Type", "application/json;charset=UTF-8"); 
            conn.setRequestProperty("Content-Length", String.valueOf(param.getBytes().length));
            conn.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            out = new PrintWriter(conn.getOutputStream());
            // 发送请求参数
            out.print(param);
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("发送 POST 请求出现异常!"+e);
            e.printStackTrace();
        }
        //使用finally块来关闭输出流、输入流
        finally{
            try{
                if(out!=null){
                    out.close();
                }
                if(in!=null){
                    in.close();
                }
            }
            catch(IOException ex){
                ex.printStackTrace();
            }
        }
        return result;
    }
    
    //测试方法
    public static void main(String[] args) {
        //发送 GET 请求
        //String s=HttpStringUtil.sendGet("http://localhost:6144/Home/RequestString", "key=123&v=456");
        //System.out.println(s);
        
        //发送 POST 请求
    	String a = "{\"token\":\"ee694d0f9bb6c6f390bdf3ad318bce00\", \"team_id\":1696, \"name\":\"个人eewew隔热\", \"file_ids\":[154093,154092], \"prices\":[{\"name\":\"deliver_address\",\"value\":\"武汉市\"}], \"archive_ids\":[5916]}";
    	String param = "{\"token\":\"ee694d0f9bb6c6f390bdf3ad318bce00\", \"team_id\":1696, \"name\":\"成功了1\", \"file_ids\":[154095,154094], \"prices\":[{\"name\":\"deliver_address\",\"value\":\"武汉市\"}], \"archive_ids\":[5916]}";
        String sr = HttpStringUtil.sendPost("http://api.yunlu6.com/api/v1/team/1696/products", a);
        System.out.println(sr);
    }

【---------------------------------------------------------------------------------main方法结果如下:--------------------------------------------------------------------------------------------】

{
    "products": {
        "id": 56411,
        "name": "个人eewew隔热",
        "category_id": 35173,
        "state": "editing",
        "goods_type": null,
        "description": null,
        "category_name": "无",
        "prices": [
            {
                "id": 63913,
                "properties": [],
                "amount": "定制",
                "money": "定制"
            }
        ],
        "files": [
            {
                "id": 63222,
                "name": null,
                "file_id": 154093
            },
            {
                "id": 63223,
                "name": null,
                "file_id": 154092
            }
        ],
        "archives": [
            {
                "id": 5916,
                "name": "3699",
                "taxonomies": []
            }
        ],
        "properties": [
            {
                "id": null,
                "product_property_id": 6,
                "value": null,
                "name": "功能/用途",
                "quotes": [],
                "children": []
            },
            {
                "id": null,
                "product_property_id": 7,
                "value": null,
                "name": "外观/形状",
                "quotes": [],
                "children": []
            },
            {
                "id": null,
                "product_property_id": 8,
                "value": null,
                "name": "工艺/设备",
                "quotes": [],
                "children": []
            },
            {
                "id": null,
                "product_property_id": 9,
                "value": null,
                "name": "原料/用料",
                "quotes": [],
                "children": []
            }
        ]
    }
}

【------------------nutz 的 action中,仅一行代码(调用util方法得到返回值;)结果如下:--------------------------------】

result:
发送 POST 请求出现异常!java.io.IOException: Server returned HTTP response code: 400 for URL: http://api.yunlu6.com/api/v1/team/1696/products
6 回复

大神快出现@wendal

我把请求参数格式化之后,不报400了,又报500。。。

仔细看了看你的代码, 感觉缺了这个

conn.setRequestMethod("POST");

@wendal 谢谢。问题解决了,我在main方法里跑,没问题,在nutz里,api那边的服务器总返回500,今天和那边联调,发现是中文编码问题。

// 获取URLConnection对象对应的输出流,设置utf-8编码
	        out = new PrintWriter(new OutputStreamWriter(conn.getOutputStream(), "utf-8"));
	        // 发送请求参数
	        out.print(params);
	        // flush输出流的缓冲
	        out.flush();
	        // 定义BufferedReader输入流来读取URL的响应,设置utf-8编码
	        in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));

把io流,转个弯,加个字符集转码一下,就好啦。

嗯,确实也忘了写post

添加回复
请先登陆
回到顶部