java http请求并返回字符串

public static String getHttpData(String url, String data) throws Exception{
        StringBuffer resultData = new StringBuffer();
        URL postUrl = new URL(url);// url到?
        HttpURLConnection connection = (HttpURLConnection) postUrl.openConnection();
        connection.setDoOutput(true);
        connection.setDoInput(true);
        connection.setRequestMethod("POST");
        connection.setUseCaches(false);
        connection.setInstanceFollowRedirects(true);
        connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        OutputStreamWriter osw = new OutputStreamWriter(connection.getOutputStream());
        osw.write(data); // data是url问号之后的所有参数集合
        osw.flush();
        osw.close();
        BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        String line;
        while ((line = reader.readLine()) != null) {
            resultData.append(line);
        }
        reader.close();
        return resultData.toString();
    }

猜你喜欢

转载自liyang678.iteye.com/blog/2298763