JAVA实现GET和POST请求

一、有关GET和POST请求的注释

1.1 有关 GET 请求的其他一些注释:

  • GET 请求可被缓存
  • GET 请求保留在浏览器历史记录中
  • GET 请求可被收藏为书签
  • GET 请求不应在处理敏感数据时使用
  • GET 请求有长度限制
  • GET 请求只应当用于取回数据(不修改)
    示例:百度api一般是get请求,除了请求地址,还有参数,?分割地址和参数:
    https://api.map.baidu.com/geocoding/v3/?address=北京市海淀区上地十街10号&output=json&ak=您的ak&callback=showLocation

1.2 有关 POST 请求的其他一些注释:

  • POST 请求不会被缓存
  • POST 请求不会保留在浏览器历史记录中
  • POST 不能被收藏为书签
  • POST 请求对数据长度没有要求

二、JAVA实现GET和POST请求

2.1 GET请求

//Get请求
public static String loadGET(String url,String param){
    StringBuilder json = new StringBuilder();
    BufferedReader in = null;
    try {
        String getUrl = url + "?" + param;
        URL requestUrl = new URL(getUrl);
        //打开和URL之间的连接
        HttpURLConnection connection = (HttpURLConnection) requestUrl.openConnection();
        //请求方式
        connection.setRequestMethod("GET");
        //设置通用的请求属性
        connection.setRequestProperty("accept", "*/*");
        connection.setRequestProperty("connection", "Keep-Alive");
        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.connect();
        //定义BufferReader输入流来读取URL的响应
        in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        String inputLine = null;
        while ( (inputLine = in.readLine()) != null) {
            json.append(inputLine);
        }
    } catch (MalformedURLException e) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("status","401");
        e.printStackTrace();
        return jsonObject.toJSONString();
    } catch (ProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if(in!=null){
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    return json.toString();
}

2.2 POST请求

public static String loadPOST(String url,String param){
    StringBuilder json = new StringBuilder();
    OutputStreamWriter out = null;
    BufferedReader in = null;
    try {
        URL requestUrl = new URL(url);
        // 打开和URL之间的连接
        HttpURLConnection connection = (HttpURLConnection) requestUrl.openConnection();
        //请求方式
        connection.setRequestMethod("POST");
        //设置通用的请求属性
        connection.setRequestProperty("accept", "*/*");
        connection.setRequestProperty("connection", "Keep-Alive");
        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");
        //DoOutput设置是否向httpUrlConnection输出,DoInput设置是否从httpUrlConnection读入,此外发送post请求必须设置这两个
        connection.setDoOutput(true);
        connection.setDoInput(true);
        //获取URLConnection对象对应的输出流
        out = new OutputStreamWriter(connection.getOutputStream(), "utf-8");
        //发送请求参数即数据
        out.write(param);
        out.flush(); // 立即充刷至请求体)PrintWriter默认先写在内存缓存中
        in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        String inputLine = null;
        while ( (inputLine = in.readLine()) != null) {
            json.append(inputLine);
        }
        connection.disconnect();
    } catch (MalformedURLException e) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("status","401");
        e.printStackTrace();
        return jsonObject.toJSONString();
    } catch (IOException e) {
        e.printStackTrace();
    }finally {
        try {
            if(out!=null){
                out.close();
            }
            if(in!=null){
                in.close();
            }
        }catch (IOException e) {
            e.printStackTrace();
        }
    }
    return json.toString();
}
  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java可以使用HTTPClient和HttpURLConnection两种方式来实现GET和POST请求。 使用HTTPClient的方法有两个版本,分别是HTTPClient3.1和HTTPClient4.5.5。HTTPClient3.1位于org.apache.commons.httpclient包下,而HTTPClient4.5.5位于org.apache.http.client包下。这两个版本都提供了对远程URL的操作工具包,可以满足工作需求。 另一种方式是使用HttpURLConnection,它是Java的标准请求方式。可以通过创建HttpURLConnection对象来发送GET和POST请求,并获取响应结果。 以下是使用HTTPClient和HttpURLConnection实现GET和POST请求的示例代码: 使用HTTPClient3.1实现GET请求: ```java HttpClient client = new HttpClient(); GetMethod method = new GetMethod(url); int statusCode = client.executeMethod(method); String response = method.getResponseBodyAsString(); ``` 使用HTTPClient4.5.5实现GET请求: ```java CloseableHttpClient client = HttpClients.createDefault(); HttpGet request = new HttpGet(url); CloseableHttpResponse response = client.execute(request); String result = EntityUtils.toString(response.getEntity()); ``` 使用HttpURLConnection实现GET请求: ```java URL url = new URL("http://example.com"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); int responseCode = connection.getResponseCode(); BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); String line; StringBuilder response = new StringBuilder(); while ((line = reader.readLine()) != null) { response.append(line); } reader.close(); ``` 使用HTTPClient4.5.5实现POST请求: ```java CloseableHttpClient client = HttpClients.createDefault(); HttpPost request = new HttpPost(url); List<NameValuePair> params = new ArrayList<>(); params.add(new BasicNameValuePair("param1", "value1")); params.add(new BasicNameValuePair("param2", "value2")); request.setEntity(new UrlEncodedFormEntity(params)); CloseableHttpResponse response = client.execute(request); String result = EntityUtils.toString(response.getEntity()); ``` 使用HttpURLConnection实现POST请求: ```java URL url = new URL("http://example.com"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); connection.setDoOutput(true); OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream()); writer.write("param1=value1&param2=value2"); writer.flush(); int responseCode = connection.getResponseCode(); BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); String line; StringBuilder response = new StringBuilder(); while ((line = reader.readLine()) != null) { response.append(line); } reader.close(); ``` 以上是使用Java实现GET和POST请求的方法,可以根据具体需求选择适合的方式来发送请求并获取响应结果。\[1\]\[2\] #### 引用[.reference_title] - *1* [用Java实现GET,POST请求](https://blog.csdn.net/lianzhang861/article/details/80364549)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] - *2* [JAVA的GET和POST请求实现方式](https://blog.csdn.net/u012513972/article/details/79569888)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值