使用java发送HTTP请求

近来在写项目时调用第三方接口,发现使用第三方接口基本都要使用java程序来发送HTTP请求到第三方的服务器去获取数据,不同的第三方提供的方法不尽相同,有使用org.apache.commons.httpclient的,有使用org.apache.http.client的,有使用org.codehaus.xfire.client,还有使用org.springframework.web.client的,个人还是比较喜欢使用java原生的java.net.URL与java.net.HttpURLConnection来发送HTTP请求,所以自己写了一个方法,共飨诸君

public static String sendHttpRequest(String url, String entity, String method) {
    BufferedReader bufferedReader = null;
    URL realUrl;
    HttpURLConnection conn = null;
    PrintWriter printWriter = null;
    String result = "";
    try {
        if ("get".equals(method)) {
            if (entity != null && !"".equals(entity)) {
                realUrl = new URL(url + "?" + entity);
            } else {
                realUrl = new URL(url);
            }
            // 根据url生成urlConnection对象
            conn = (HttpURLConnection) realUrl.openConnection();
           /* conn.connect();可以不明文设定连接,conn.getInputStream()会自动连接*/
        } else if ("post".equals(method)) {
            realUrl = new URL(url);
            conn = (HttpURLConnection) realUrl.openConnection();
            conn.setRequestMethod("POST");/*设定请求的方法为"POST",默认是GET */
            if (entity != null && !"".equals(entity)) {
                // 设置是否从httpUrlConnection读入,默认情况下是true;
                conn.setDoInput(true);
                /*设置是否向httpUrlConnection输出,因为这个是post请求,参数要放在 http正文内,因此需要设为true, 默认情况下是false*/
                conn.setDoOutput(true);
                // Post 请求不能使用缓存
                conn.setUseCaches(false);
                conn.connect();
                printWriter = new PrintWriter(conn.getOutputStream());
                printWriter.print(entity);
                printWriter.flush();
            }
        }else{
            throw new IllegalArgumentException("请输入正确的请求方式");
        }
        bufferedReader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String line;
        if ((line = bufferedReader.readLine()) != null) {
            result += line;
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            if (printWriter != null) {
                printWriter.close();
            }
            if (bufferedReader != null) {
                bufferedReader.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return result;
    }

}
测试方法如下:<特意测试了post请求,请求参数为null的情况>

 
 
public static void main(String[] args) {
    String str = "userMobile=15539266567&usertype=0";
    System.out.println(sendHttpRequest("http://localhost:8080/mine/try", null, "get"));
    System.out.println(sendHttpRequest("http://localhost:8080/mine/your/best", str, "post"));
    System.out.println(sendHttpRequest("http://localhost:8080/mine/so/amazing", null, "post"));
}
在控制台打印输出,哈哈,是不是很完美。关于PUT请求与DELETE请求与POST请求类似,不再敖述。

false
1
{"StageCategory":[{"id":"001","name":"第一阶段"},{"id":"002","name":"第二阶段"},{"id":"003","name":


猜你喜欢

转载自blog.csdn.net/frozenkevin/article/details/55095230