JAVA工具类---URLUtil

package com.evay.utils;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ConnectException;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * @description 描述:调用http接口返回结果
 */

public class URLTest {
    public static void main(String[] args) {
        String requestUrl="http://passport.sdcom.gov.cn/api/signLogin?sign=566b9a6ed0e31e11b14d35cd390b69981499236659208806&account=admin@sdswt&appID=ZYCLTZS"; 
        String result = httpRequest(requestUrl,"GET",null);
        System.out.println(result); 
    }
    
    public static String httpRequest(String requestUrl, String requestMethod, String outputStr) {
        String json = null;
        StringBuffer buffer = new StringBuffer();
        try {
            URL url = new URL(requestUrl);
            HttpURLConnection httpUrlConn = (HttpURLConnection) url.openConnection();
            httpUrlConn.setDoOutput(true);
            httpUrlConn.setDoInput(true);
            httpUrlConn.setUseCaches(false);
            // 设置请求方式(GET/POST)
            httpUrlConn.setRequestMethod(requestMethod);

            if ("GET".equalsIgnoreCase(requestMethod))
                httpUrlConn.connect();

            // 当有数据需要提交时
            if (null != outputStr) { System.out.println("outputStr=="+outputStr);
                OutputStream outputStream = httpUrlConn.getOutputStream();
                // 注意编码格式,防止中文乱码
                outputStream.write(outputStr.getBytes("UTF-8"));
                outputStream.close();
            }

            // 将返回的输入流转换成字符串
            InputStream inputStream = httpUrlConn.getInputStream(); System.out.println("inputStream=="+inputStream);
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            String str = null;
            while ((str = bufferedReader.readLine()) != null) {
                buffer.append(str);
            }
            bufferedReader.close();
            inputStreamReader.close();
            // 释放资源
            inputStream.close();
            inputStream = null;
            httpUrlConn.disconnect();  
            json = buffer.toString();          
        } catch (ConnectException ce) {
           // log.error(" server connection timed out.");
            System.out.println("连接超时" + ce);
        } catch (Exception e) {
            //log.error("http request error:{}", e);
            System.out.println("http请求异常" + e);
        }
        return json;
    }


}

展开阅读全文

没有更多推荐了,返回首页