给登录功能优化了一波,前面重复的代码提取了出来:
将前面固定的请求头、请求方法、url等设置提取到了Connection类中;
package common;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
public class Connection {
public static HttpURLConnection getConnection(String urlPath,String method){
URL url = null;
HttpURLConnection connection = null;
try {
url = new URL(urlPath);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestProperty("Content-Type","application/json; charset=UTF-8");
connection.setRequestMethod(method);
connection.setDoOutput(true);
connection.setDoInput(true);
connection.connect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return connection;
}
}
将返回值定义成一个对象:
JsonRootBean jsonRootBean = (JsonRootBean)JSONObject.toBean(resultJson,JsonRootBean.class);
完整代码:
public String login(){
String result = null;
try {
HttpURLConnection connection = Connection.getConnection("http://192.168.30.35:8080/v1/user/login","POST");
//请求数据
DataOutputStream out = new DataOutputStream(connection.getOutputStream());
JSONObject date = new JSONObject();
date.put("userName","admin");
date.put("password","96e79218965eb72c92a549dd5a330112");
String json = date.toString();
// System.out.println("打印得json:"+json);
out.writeBytes(json);
out.flush();
out.close();
//返回
InputStream inputStream = connection.getInputStream();
BufferedReader res = new BufferedReader(new InputStreamReader(inputStream));
String result1 = res.readLine();
// System.out.println(result1);
JSONObject resultJson =JSONObject.fromObject(result1);
//tobin将resultJson json对象转换为Java对象
JsonRootBean jsonRootBean = (JsonRootBean)JSONObject.toBean(resultJson,JsonRootBean.class);
System.out.println(jsonRootBean.getResult().getToken());
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。