HttpURLConnection 发送网络请求的基本设置

public Result requestTest(String method, String param, String httpUrl){
    String resultStr = "";
    try {
        //转换为字节数组
        byte[] data = new String(param.getBytes(), CHARSET).getBytes();
        URL http = new URL(httpUrl);
        HttpURLConnection conn = (HttpURLConnection) http.openConnection();
        conn.setReadTimeout(10000);
        conn.setConnectTimeout(10000);

        // 设置文件字符集:
        conn.setRequestProperty("Charset", CHARSET);
        // 设置文件类型:
        conn.setRequestProperty("Content-Type", "application/json");

        // 设置文件长度
        conn.setRequestProperty("Content-Length", String.valueOf(data.length));
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setRequestMethod(method);

        // 开始连接请求
        conn.connect();
        OutputStream out = conn.getOutputStream();
        // 写入请求的字符串secret
        out.write(data);

        System.out.println(conn.getResponseCode());
        if (conn.getResponseCode() == 200) {
            byte[] buff = getByte(conn.getInputStream());
            // 转成字符串
            resultStr = new String(buff, CHARSET);
            System.out.println(resultStr);

        } else {
            System.out.println("no++");
        }
        out.flush();
        out.close();
    }catch (NoHttpResponseException e) {
        // 无服务器响应
        return ResultGenerator.genFailResult("无服务器响应");
    } catch (ConnectTimeoutException e) {
        // 捕获ConnectionTimeout
        return ResultGenerator.genFailResult("ConnectionTimeout");
    } catch (SocketTimeoutException e) {
        // 捕获SocketTimeout
        return ResultGenerator.genFailResult("SocketTimeout");
    } catch (Exception e) {
        // 其他异常
        return ResultGenerator.genFailResult("其他异常");
    }

    return ResultGenerator.genSuccessResult();
}

你可能感兴趣的:(Java)