post請求設置content-type

public String sendPost(String url, String param) {
    PrintWriter out = null;
    BufferedReader in = null;
    String result = "";
    try {
        URL realUrl = new URL(url);
        URLConnection connection = realUrl.openConnection();
        connection.setReadTimeout(60 * 1000);
        connection.setConnectTimeout(30 * 1000);
        connection.setRequestProperty("connection", "Keep-Alive");
        connection.setRequestProperty("accept", "*/*");
        connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
        connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
        connection.setDoInput(true);
        connection.setDoOutput(true);
        out = new PrintWriter(connection.getOutputStream());
        out.print(param);
        out.flush();
        String line;
        in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        while ((line = in.readLine()) != null) {
            result += line;
        }
    } catch (Exception e) {
        logger.error("請求出現異常!" + e);
        result = "-99";
    } finally {
        try {
            if (out != null) {
                out.close();
            }
            if (in != null) {
                in.close();
            }
        } catch (IOException e) {
            logger.error("請求出現異常!" + e);
        }
    }
    return result;
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章