JavaWeb之发送Get请求和Post请求的封装类

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/weixin_40931184/article/details/81015148
import java.io.BufferedReader;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLDecoder;

import net.sf.json.JSONObject;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

/**
 * @author 作者 macx:
 * @version 创建时间:2018年7月12日 下午2:20:47 类说明
 */
@SuppressWarnings({"deprecation"})
public class Test_1 {

    public static void main(String[] args) {
          sendPost("","params");
    }

    /**
     * 向指定 URL 发送POST方法的请求
     */
    private static String sendPost(String url, String param) {
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            // 设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            out = new PrintWriter(conn.getOutputStream());
            // 发送请求参数
            out.print(param);
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("发送 POST 请求出现异常!" + e);
            e.printStackTrace();
        } finally {// 使用finally块来关闭输出流、输入流
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return result;
    }

   

     /**
         * 向指定 URL 发送GET方法的请求
         */

    public static JSONObject httpGet(String url) {

        // get请求返回结果
        JSONObject jsonResult = null;
        try {
            DefaultHttpClient client = new DefaultHttpClient();
            // 发get请求
            HttpGet request = new HttpGet(url);
            HttpResponse response = client.execute(request);
            /** 请求发求成功,并得到响应 **/
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                /** 读取服务器返回过来的json字符串数 **/
                String strResult = EntityUtils.toString(response.getEntity());
                System.out.println(strResult);
                /** 把json字符串转换成json对象 **/
                try {
                    jsonResult = JSONObject.fromObject(strResult);
                    url = URLDecoder.decode(url, "UTF-8");
                } catch (Exception e) {
                    jsonResult = new JSONObject();
                    jsonResult.put("id", strResult);
                }
            } else {
                System.out.println("get请求提交失败:" + url);
            }
            ((Closeable) client).close();
        } catch (IOException e) {
            System.out.println("get请求提交失败:" + url);
        }
        return jsonResult;
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_40931184/article/details/81015148