当前位置: 首页 > wzjs >正文

网站项目建设方案文档网站前端设计外包公司

网站项目建设方案文档,网站前端设计外包公司,网站布局设计工具,5种有效增加网站流量【Java】实现后端请求接口 【一】使用 HttpURLConnection 实现四种请求方式的示例【1】Get请求【2】POST请求【3】PUT请求【4】DELETE 请求【5】汇总工具类,通过传参实现4种请求 【二】HttpClient 实现四种请求方式的示例【1】GET请求【2】POST 请求【3】PUT 请求【…

【Java】实现后端请求接口

  • 【一】使用 HttpURLConnection 实现四种请求方式的示例
    • 【1】Get请求
    • 【2】POST请求
    • 【3】PUT请求
    • 【4】DELETE 请求
    • 【5】汇总工具类,通过传参实现4种请求
  • 【二】HttpClient 实现四种请求方式的示例
    • 【1】GET请求
    • 【2】POST 请求
    • 【3】PUT 请求
    • 【4】DELETE 请求
    • 【5】汇总的工具类

【一】使用 HttpURLConnection 实现四种请求方式的示例

HttpURLConnection 是 Java 标准库中较早提供的 HTTP 请求工具

【1】Get请求

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;public class HttpGetExample {public static String sendGet(String urlStr) throws Exception {// 对 URL 中的中文参数进行编码String encodedUrl = URLEncoder.encode(urlStr, "UTF-8").replaceAll("\\+", "%20");URL url = new URL(encodedUrl);HttpURLConnection connection = (HttpURLConnection) url.openConnection();connection.setRequestMethod("GET");// 设置请求头,指定接收的字符编码connection.setRequestProperty("Accept-Charset", "UTF-8");int responseCode = connection.getResponseCode();if (responseCode == HttpURLConnection.HTTP_OK) {// 使用 BufferedReader 读取响应内容,并指定字符编码为 UTF-8BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));StringBuilder response = new StringBuilder();String line;while ((line = reader.readLine()) != null) {response.append(line);}reader.close();return response.toString();}return null;}public static void main(String[] args) {try {String url = "http://example.com/api?param=中文参数";String response = sendGet(url);System.out.println(response);} catch (Exception e) {e.printStackTrace();}}
}

【2】POST请求

import java.io.DataOutputStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;public class HttpPostExample {public static String sendPost(String urlStr, String params) throws Exception {URL url = new URL(urlStr);HttpURLConnection connection = (HttpURLConnection) url.openConnection();connection.setRequestMethod("POST");// 设置请求头,指定字符编码和内容类型connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");connection.setRequestProperty("Accept-Charset", "UTF-8");connection.setDoOutput(true);// 对请求参数进行编码String encodedParams = URLEncoder.encode(params, "UTF-8");DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());outputStream.writeBytes(encodedParams);outputStream.flush();outputStream.close();int responseCode = connection.getResponseCode();if (responseCode == HttpURLConnection.HTTP_OK) {// 使用 BufferedReader 读取响应内容,并指定字符编码为 UTF-8BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));StringBuilder response = new StringBuilder();String line;while ((line = reader.readLine()) != null) {response.append(line);}reader.close();return response.toString();}return null;}public static void main(String[] args) {try {String url = "http://example.com/api";String params = "param=中文参数";String response = sendPost(url, params);System.out.println(response);} catch (Exception e) {e.printStackTrace();}}
}

【3】PUT请求

import java.io.DataOutputStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;public class HttpPutExample {public static String sendPut(String urlStr, String params) throws Exception {URL url = new URL(urlStr);HttpURLConnection connection = (HttpURLConnection) url.openConnection();connection.setRequestMethod("PUT");// 设置请求头,指定字符编码和内容类型connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");connection.setRequestProperty("Accept-Charset", "UTF-8");connection.setDoOutput(true);// 对请求参数进行编码String encodedParams = URLEncoder.encode(params, "UTF-8");DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());outputStream.writeBytes(encodedParams);outputStream.flush();outputStream.close();int responseCode = connection.getResponseCode();if (responseCode == HttpURLConnection.HTTP_OK) {// 使用 BufferedReader 读取响应内容,并指定字符编码为 UTF-8BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));StringBuilder response = new StringBuilder();String line;while ((line = reader.readLine()) != null) {response.append(line);}reader.close();return response.toString();}return null;}public static void main(String[] args) {try {String url = "http://example.com/api";String params = "param=中文参数";String response = sendPut(url, params);System.out.println(response);} catch (Exception e) {e.printStackTrace();}}
}

【4】DELETE 请求

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;public class HttpDeleteExample {public static String sendDelete(String urlStr) throws Exception {// 对 URL 中的中文参数进行编码String encodedUrl = URLEncoder.encode(urlStr, "UTF-8").replaceAll("\\+", "%20");URL url = new URL(encodedUrl);HttpURLConnection connection = (HttpURLConnection) url.openConnection();connection.setRequestMethod("DELETE");// 设置请求头,指定接收的字符编码connection.setRequestProperty("Accept-Charset", "UTF-8");int responseCode = connection.getResponseCode();if (responseCode == HttpURLConnection.HTTP_OK) {// 使用 BufferedReader 读取响应内容,并指定字符编码为 UTF-8BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));StringBuilder response = new StringBuilder();String line;while ((line = reader.readLine()) != null) {response.append(line);}reader.close();return response.toString();}return null;}public static void main(String[] args) {try {String url = "http://example.com/api?param=中文参数";String response = sendDelete(url);System.out.println(response);} catch (Exception e) {e.printStackTrace();}}
}

【5】汇总工具类,通过传参实现4种请求

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;public class HttpUtils {public static String sendRequest(String urlStr, String method, String params) {try {URL url;if (method.equalsIgnoreCase("GET") || method.equalsIgnoreCase("DELETE")) {if (params != null) {urlStr += "?" + URLEncoder.encode(params, "UTF-8").replaceAll("\\+", "%20");}url = new URL(urlStr);} else {url = new URL(urlStr);}HttpURLConnection connection = (HttpURLConnection) url.openConnection();connection.setRequestMethod(method);// 设置请求头,指定字符编码和接收内容的字符编码connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");connection.setRequestProperty("Accept-Charset", "UTF-8");if (method.equalsIgnoreCase("POST") || method.equalsIgnoreCase("PUT")) {connection.setDoOutput(true);if (params != null) {String encodedParams = URLEncoder.encode(params, "UTF-8");DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());outputStream.writeBytes(encodedParams);outputStream.flush();outputStream.close();}}int responseCode = connection.getResponseCode();if (responseCode == HttpURLConnection.HTTP_OK) {// 使用 BufferedReader 读取响应内容,并指定字符编码为 UTF-8BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));StringBuilder response = new StringBuilder();String line;while ((line = reader.readLine()) != null) {response.append(line);}reader.close();return response.toString();}} catch (Exception e) {e.printStackTrace();}return null;}public static void main(String[] args) {String url = "http://example.com/api";String params = "param=中文参数";String getResponse = sendRequest(url, "GET", params);System.out.println("GET Response: " + getResponse);String postResponse = sendRequest(url, "POST", params);System.out.println("POST Response: " + postResponse);String putResponse = sendRequest(url, "PUT", params);System.out.println("PUT Response: " + putResponse);String deleteResponse = sendRequest(url + "?" + params, "DELETE", null);System.out.println("DELETE Response: " + deleteResponse);}
}

【二】HttpClient 实现四种请求方式的示例

HttpClient 是 Java 11 及以上版本引入的新的 HTTP 客户端,使用起来更加简洁和方便。

【1】GET请求

import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;public class HttpClientGetExample {public static void main(String[] args) {try {// 创建 HttpClient 实例HttpClient client = HttpClient.newHttpClient();// 构建 GET 请求,指定请求 URLHttpRequest request = HttpRequest.newBuilder().uri(URI.create("https://example.com/api?param=中文参数")).header("Accept-Charset", "UTF-8") // 设置接收响应的字符编码为 UTF-8.GET().build();// 发送请求并获取响应,指定响应体处理方式为按 UTF-8 编码读取字符串HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());System.out.println("Status code: " + response.statusCode());System.out.println("Response body: " + response.body());} catch (IOException | InterruptedException e) {e.printStackTrace();}}
}

【2】POST 请求

import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;public class HttpClientPostExample {public static void main(String[] args) {try {// 构建请求体,对中文参数进行编码String param = URLEncoder.encode("中文参数", StandardCharsets.UTF_8);String requestBody = "param=" + param;// 创建 HttpClient 实例HttpClient client = HttpClient.newHttpClient();// 构建 POST 请求,设置请求头的字符编码和内容类型HttpRequest request = HttpRequest.newBuilder().uri(URI.create("https://example.com/api")).header("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8").header("Accept-Charset", "UTF-8").POST(HttpRequest.BodyPublishers.ofString(requestBody)).build();// 发送请求并获取响应,指定响应体处理方式为按 UTF-8 编码读取字符串HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());System.out.println("Status code: " + response.statusCode());System.out.println("Response body: " + response.body());} catch (IOException | InterruptedException e) {e.printStackTrace();}}
}

【3】PUT 请求

import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;public class HttpClientPutExample {public static void main(String[] args) {try {// 构建请求体,对中文参数进行编码String param = URLEncoder.encode("中文参数", StandardCharsets.UTF_8);String requestBody = "param=" + param;// 创建 HttpClient 实例HttpClient client = HttpClient.newHttpClient();// 构建 PUT 请求,设置请求头的字符编码和内容类型HttpRequest request = HttpRequest.newBuilder().uri(URI.create("https://example.com/api")).header("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8").header("Accept-Charset", "UTF-8").PUT(HttpRequest.BodyPublishers.ofString(requestBody)).build();// 发送请求并获取响应,指定响应体处理方式为按 UTF-8 编码读取字符串HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());System.out.println("Status code: " + response.statusCode());System.out.println("Response body: " + response.body());} catch (IOException | InterruptedException e) {e.printStackTrace();}}
}

【4】DELETE 请求

import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;public class HttpClientDeleteExample {public static void main(String[] args) {try {// 创建 HttpClient 实例HttpClient client = HttpClient.newHttpClient();// 构建 DELETE 请求,指定请求 URL 和接收响应的字符编码HttpRequest request = HttpRequest.newBuilder().uri(URI.create("https://example.com/api?param=中文参数")).header("Accept-Charset", "UTF-8").DELETE().build();// 发送请求并获取响应,指定响应体处理方式为按 UTF-8 编码读取字符串HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());System.out.println("Status code: " + response.statusCode());System.out.println("Response body: " + response.body());} catch (IOException | InterruptedException e) {e.printStackTrace();}}
}

【5】汇总的工具类

HttpClientUtils 类中的 sendRequest 方法根据传入的 url、method 和 requestBody 构建相应的 HttpRequest 对象并发送请求。对于 GET 和 DELETE 请求,requestBody 可以传入 null;对于 POST 和 PUT 请求,需要传入请求体内容。在 main 方法中演示了如何调用该工具类的方法进行不同类型的请求。

(1)在请求头中设置 Accept-Charset 为 UTF-8,告诉服务器客户端期望接收的字符编码。
(2)对于 POST 和 PUT 请求,使用 URLEncoder 对请求体中的中文参数进行编码,避免发送时出现乱码。
(3)使用 HttpResponse.BodyHandlers.ofString() 接收响应体,默认以 UTF - 8 编码读取字符串。

import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;public class HttpClientUtils {private static final HttpClient client = HttpClient.newHttpClient();public static String sendRequest(String url, String method, String requestBody) {try {HttpRequest.Builder requestBuilder = HttpRequest.newBuilder().uri(URI.create(url)).header("Accept-Charset", "UTF-8");switch (method.toUpperCase()) {case "GET":requestBuilder.GET();break;case "POST":if (requestBody != null) {requestBody = URLEncoder.encode(requestBody, StandardCharsets.UTF_8);}requestBuilder.header("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8").POST(HttpRequest.BodyPublishers.ofString(requestBody));break;case "PUT":if (requestBody != null) {requestBody = URLEncoder.encode(requestBody, StandardCharsets.UTF_8);}requestBuilder.header("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8").PUT(HttpRequest.BodyPublishers.ofString(requestBody));break;case "DELETE":requestBuilder.DELETE();break;default:throw new IllegalArgumentException("Unsupported HTTP method: " + method);}HttpRequest request = requestBuilder.build();HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());return response.body();} catch (IOException | InterruptedException | IllegalArgumentException e) {e.printStackTrace();return null;}}public static void main(String[] args) {String getUrl = "https://example.com/api?param=中文参数";String postUrl = "https://example.com/api";String putUrl = "https://example.com/api";String deleteUrl = "https://example.com/api?param=中文参数";String postBody = "param=中文参数";String putBody = "param=中文参数";System.out.println("GET response: " + sendRequest(getUrl, "GET", null));System.out.println("POST response: " + sendRequest(postUrl, "POST", postBody));System.out.println("PUT response: " + sendRequest(putUrl, "PUT", putBody));System.out.println("DELETE response: " + sendRequest(deleteUrl, "DELETE", null));}
}

文章转载自:

http://Bs9ya5JE.hgbzc.cn
http://8pB63p5b.hgbzc.cn
http://yT8SY66h.hgbzc.cn
http://IWsy5ahW.hgbzc.cn
http://erlq1cMB.hgbzc.cn
http://6X1Obm2X.hgbzc.cn
http://RuHwwhHp.hgbzc.cn
http://kkULSOt1.hgbzc.cn
http://er18KLmY.hgbzc.cn
http://A9PVVxPD.hgbzc.cn
http://lD7egoUZ.hgbzc.cn
http://ChO8Gurr.hgbzc.cn
http://eQJcdr0V.hgbzc.cn
http://4jgEnsr0.hgbzc.cn
http://Jim3y24U.hgbzc.cn
http://429ogrtv.hgbzc.cn
http://ndQRgAPC.hgbzc.cn
http://ZsxyZiWb.hgbzc.cn
http://PDn2Bix4.hgbzc.cn
http://OPwVoAzG.hgbzc.cn
http://SVOIVQ07.hgbzc.cn
http://Hsra8aJ9.hgbzc.cn
http://13iGZOzr.hgbzc.cn
http://5GBxl4sd.hgbzc.cn
http://08jTCs1O.hgbzc.cn
http://Z0P5Ao27.hgbzc.cn
http://t1KLWXjN.hgbzc.cn
http://JQs6wpFM.hgbzc.cn
http://3eXOkR4C.hgbzc.cn
http://rGma88XE.hgbzc.cn
http://www.dtcms.com/wzjs/742728.html

相关文章:

  • 织梦 网站统计网站地图怎么生成
  • 做网站后的收获wordpress前缀有哪些
  • 网站品牌形象设计怎么做钉钉企业注册流程
  • 秦皇岛网站制作方案杭州淘策网站开发
  • 爱网站关键词挖掘网站的图片要会员才能下载怎么做
  • 邵阳建设网站wordpress赞踩插件
  • 做网站是怎么挣钱的全国十大广告公司
  • 短信验证码接码网站建设上海政务网站建设
  • 建筑工人app电商网站怎样做优化才最合理
  • 网站seo课设返利导购网站建设需求文档
  • 网站建设热门吗正规手机网站怎么做
  • 网络服务商网站百度站长之家
  • 东莞北京网站建设价格wordpress登陆错误500
  • 网站域名建设费进什么科目秋林 做网站
  • 扬州网站建设哪家好中信银行官网
  • 网络营销网站推广wordpress怎么建立网站吗
  • 官网百度苏州seo优化公司
  • 国外空间设计网站wordpress ip设置
  • 为网站做外链的文章中科院网站建设
  • 揭阳模板网站建站协达网站建设
  • .net是建网站的吗国外服务器购买
  • WordPress仿站助手seo百科大全
  • 宁波建网站哪家wordpress商家插件
  • 网站下载佛山网站优化效果
  • 长沙cms模板建站溧阳做网站
  • html5做网站导航建设网站的公司济南兴田德润o简介图片
  • icp备案网站快速备案专家公司名字大全10000个
  • 公司网站怎么做动力做网站
  • 苏州网站建设公司排名朝阳开发公司
  • 奉节网站建设公司Wordpress已有数据库表