利用Java的HttpURLConnection进行远程url请求(调用远程接口)
测试类:请求类型为json,以post方式请求,利用OutputStream写入数据
实体类:public class User implementsSerializable {privateString name;privateString password;publicString getName() {returnname;
}public voidsetName(String name) {this.name =name;
}publicString getPassword() {returnpassword;
}public voidsetPassword(String password) {this.password =password;
}
}-------@RunWith(SpringRunner.class)
@SpringBootTestpublic classSpringboot02ApplicationTests {
@AutowiredprivateUserService userService;
@Testpublic voidcontextLoads(){
User user= newUser();
user.setName("lisi");
user.setPassword("123");//调用远程接口方法,获取返回结果类型
String result =userService.idendifyUser(user);
System.out.println(result);
}
}---------@Servicepublic class UserServiceImpl implementsUserService {publicString idendifyUser(User user){//将对象转换为json,然后发送;
String json =JSONObject.fromObject(user).toString();
String result= null;try{
result=UserRemoteVerify.doPost(json);
}catch(Exception e){
e.printStackTrace();
}returnresult;
}
}---------
/*** 调用远程接口,验证用户数据是否合理*/
public classUserRemoteVerify {//post请求
public static String doPost(String json) throwsException{//创建URL对象,设置请求url
URL url = new URL("http://127.0.0.1:8089/user/service");//调用URL对象的openConnection( )来获取HttpURLConnection对象实例
HttpURLConnection conn =(HttpURLConnection)url.openConnection();//请求方法为POST
conn.setRequestMethod("POST");//设置连接超时为5秒
conn.setConnectTimeout(5000);//允许输入输出
conn.setDoInput(true);
conn.setDoOutput(true);//不能缓存
conn.setUseCaches(false);//至少要设置的两个请求头//设置头部信息
conn.setRequestProperty("headerdata", "ceshiyongde");//一定要设置 Content-Type 要不然服务端接收不到参数
conn.setRequestProperty("Content-Type", "application/Json; charset=UTF-8");//输出流包含要发送的数据,要注意数据格式编码
OutputStream op=conn.getOutputStream();
op.write(json.getBytes());//服务器返回东西了,先对响应码判断
String result = null;if (conn.getResponseCode() == 200) {//用getInputStream()方法获得服务器返回的输入流
InputStream in =conn.getInputStream();//流转换为二进制数组,read()是转换方法
byte[] data = new byte[1024];
in.read(data);
result= new String(data, "UTF-8");
in.close();returnresult;
}returnresult;
}
}-------------远程服务端代码
@Controllerpublic classUserController {/*** 使用json接收客户端请求,返回json数据;url="http://127.0.0.1:8089/user/service"*/@PostMapping("user/service")
@ResponseBodypublic String dealUserForJson(HttpServletRequest request)throwsException{//调用处理服务,对远程数据进行校验,返回对应的结果
String result =UserRemoteHandle.verifyUser(request);returnresult;
}
}--------
/*** 处理远程数据验证*/
public classUserRemoteHandle {/*** 验证远程用户信息,若正确,则返回成功;否则返回失败*/
public static String verifyUser(HttpServletRequest request) throwsException{//根据HttpServletRequest获取输入流对象
InputStream inputStream = null;try{
inputStream=request.getInputStream();//使用byte[]数组存储接收到的数据
byte[] bytes = new byte[1024];//从输入流中将数据读取到bytes中
inputStream.read(bytes);//将bytes转换为字符串类型
String json = newString(bytes);//int i = 1/0;//服务端异常测试
if(StringUtils.isNotBlank(json)){
JSONObject jsonObject=JSONObject.fromObject(json);//将json类型转换为对象
User user = (User)JSONObject.toBean(jsonObject,User.class);//判断用户名和密码是否正确;假设用户名:lisi,密码:123;
if(user.getName().equals("lisi") && user.getPassword().equals("123")){return "success";
}
}
}catch(Exception e){
e.printStackTrace();return "服务端出现异常";
}finally { //释放资源
if(inputStream != null){
inputStream.close();
}
}//数据不符,返回错误信息
return "message is error";
}
}