HTTP-POST请求

public class HttpUtil {

public static String doPost(String url, String param, int timeOut,String miyue)  throws IOException {

    JSONObject oJson = JSONObject.parseObject(param);
    param = oJson.toJSONString();
    EncryptUtils eu = new EncryptUtils();
    String sign = eu.md5Digest(param+timestamp+bssKey).toLowerCase();
    url+="?timestamp="+timestamp+"&sign="+sign;
 PrintWriter out = null;
    OutputStreamWriter out = null;
    BufferedReader in = null;
    String result = "";
    try {
        URL realUrl = new URL(url);

        URLConnection conn = realUrl.openConnection();

        conn.setRequestProperty("accept", "*/*");
        conn.setRequestProperty("connection", "Keep-Alive");
        conn.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
        conn.setConnectTimeout(timeOut);
        conn.setDoOutput(true);
        conn.setDoInput(true);

     out = new PrintWriter(conn.getOutputStream());
        out =new OutputStreamWriter(conn.getOutputStream(), "UTF-8");

        out.write(param);

/ out.print(param);

        out.flush();
        // 定义BufferedReader输入流来读取URL的响应
        in = new BufferedReader(
                new InputStreamReader(conn.getInputStream(),"utf-8"));
        String line;
        while ((line = in.readLine()) != null) {
            result += line;
        }
    } catch (Throwable e) {
        throw new IOException(e);
    }
    // 使用finally块来关闭输出流、输入流
    finally {
        if (out != null) {
            try {
                out.close();
            } catch (Throwable ex) {
                ex.printStackTrace();
            }
        }
        if (in != null) {
            try {
                in.close();
            } catch (Throwable ex) {
                ex.printStackTrace();
            }
        }
    }
    return result;
}

}

猜你喜欢

转载自blog.51cto.com/12439947/2467084
今日推荐