欢迎访问我的个人博客:https://ddddddddd.top
搬运请注明
使用URLConnection发送HTTP请求
使用URLConnection的原因
是这样一个情景
现在有一个服务,提供了api接口,我们要去请求它来获取数据
只能使用jdk1.8
原先是想直接写一个前端通过ajax来请求,但是会碰到跨域问题
了解了几种解决跨域问题的几种方案,发现都需要后端的配合,但我只有一个api接口
所以决定直接使用java程序来发起http请求,经测试是没有跨域问题的
启动被请求服务
请求api接口
http://localhost:8081/postRequest/
我们模拟一下api接口,接收的是一个User类型的json数据.
编写URLConnection
我们在这边写java程序来进行post请求
public class URLConnectionUtil {
public static String createURLConnection(String Url,String Port) throws Exception {
User user=new User();
user.setUsername("admin");
user.setAge(18);
String parameterData = user.toString();
System.out.println(parameterData);
URL localURL = new URL("http://localhost:8081/postRequest/");
URLConnection connection = localURL.openConnection();
HttpURLConnection httpURLConnection = (HttpURLConnection)connection;
httpURLConnection.setDoOutput(true);
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setRequestProperty("Accept-Charset", "utf-8");
// httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
httpURLConnection.setRequestProperty("Content-Type", "application/json");
httpURLConnection.setRequestProperty("Content-Length", String.valueOf(parameterData.length()));
OutputStream outputStream = null;
OutputStreamWriter outputStreamWriter = null;
InputStream inputStream = null;
InputStreamReader inputStreamReader = null;
BufferedReader reader = null;
StringBuffer resultBuffer = new StringBuffer();
String tempLine = null;
try {
outputStream = httpURLConnection.getOutputStream();
outputStreamWriter = new OutputStreamWriter(outputStream);
outputStreamWriter.write(parameterData.toString());
outputStreamWriter.flush();
if (httpURLConnection.getResponseCode() >= 300) {
throw new Exception("HTTP Request is not success, Response code is " + httpURLConnection.getResponseCode());
}
inputStream = httpURLConnection.getInputStream();
inputStreamReader = new InputStreamReader(inputStream);
reader = new BufferedReader(inputStreamReader);
while ((tempLine = reader.readLine()) != null) {
resultBuffer.append(tempLine);
}
} finally {
if (outputStreamWriter != null) {
outputStreamWriter.close();
}
if (outputStream != null) {
outputStream.close();
}
if (reader != null) {
reader.close();
}
if (inputStreamReader != null) {
inputStreamReader.close();
}
if (inputStream != null) {
inputStream.close();
}
}
return resultBuffer.toString();
}
}
json数据转换
看下这个实体类的toString方法
在这里我是重写了这个方法,因为只能使用jdk1.8 无法引入外部jar包,所以我不晓得怎么转换json数据,只能用拼接字符串的方法把entity转成json方法,如果有大佬晓得怎么用jdk来写json转换的方法请务必告知
发起请求
这个是请求端,可以看到发送的json数据以及接收的json数据
这里是服务端,可以看到请求过来的数据