想要具体实现的代码,获取完之后能保存至数据库中,初学者,代码能给我加个注释最好了,谢谢
首先给你一个后台发送请求的:
httpUtils
通过这个HttpUtils得到的一般是Json格式的字符串。
再给你一个处理json(与后台常用的数据结构相互转换关系的地址)
Json处理
1.首先请求下接口的,然后请求下数据结构,比如我请求一个接口自己定义的localhost:7070/users
{
"code": 200,
"message": " Operation is successful.",
"data": {
"total": 1,
"list": [
{
"id": 2,
"username": "1190347",
"employeeId": "1190347",
"firstName": "Chen",
"lastName": "Wang",
"nickName": "Chen",
"birthday": "1980-11-02",
"age": 24,
"gender": "male",
"kind": 1,
"status": 1,
"phone": "0422739856",
"phoneStandby": "0422739811",
"phoneEmergency": "0422739823",
"email": "chenwang@ewe.com.au",
"residentialAddress": "Unit 2,21 Worth St,Chullora,NSW 2190",
"localName": "李四",
"lastLoginDate": "2017-12-03 00:02:45",
"lastLogoutDate": "2017-12-03 04:10:10"
}
]
}
}
返回了一个json数据。
json数据的遍历会吧?拿个以上的例子
得到数据就可以在java定义一个和data里面数据类型一样的类
package com.ewe.core.model;
import java.util.Date;
import org.hibernate.validator.constraints.Email;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
@JsonIgnoreProperties({"password"})
public class Users {
private Integer id;
private String username;
private String password;
private String employeeId;
private String firstName;
private String lastName;
private String nickName;
@JsonFormat(pattern="yyyy-MM-dd")
private Date birthday;
private Short age;
private String gender;
private Short kind;
private Short status;
private String phone;
private String phoneStandby;
private String phoneEmergency;
private String email;
private String residentialAddress;
@JsonProperty("lastLoginDate")
@JsonFormat(pattern="yyyy-MM-dd HH:mm:ss")
private Date lastLoginDate;
@JsonFormat(pattern="yyyy-MM-dd HH:mm:ss")
@JsonProperty("lastLogoutDate")
private Date lastLogoutDate;
private String localName;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username == null ? null : username.trim();
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password == null ? null : password.trim();
}
public String getEmployeeId() {
return employeeId;
}
public void setEmployeeId(String employeeId) {
this.employeeId = employeeId == null ? null : employeeId.trim();
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName == null ? null : firstName.trim();
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName == null ? null : lastName.trim();
}
public String getLocalName() {
return localName;
}
public void setLocalName(String localName) {
this.localName = localName == null ? null : localName.trim();
}
public String getNickName() {
return nickName;
}
public void setNickName(String nickName) {
this.nickName = nickName == null ? null : nickName.trim();
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public Short getAge() {
return age;
}
public void setAge(Short age) {
this.age = age;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender == null ? null : gender.trim();
}
public Short getKind() {
return kind;
}
public void setKind(Short kind) {
this.kind = kind;
}
public Short getStatus() {
return status;
}
public void setStatus(Short status) {
this.status = status;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone == null ? null : phone.trim();
}
public String getPhoneStandby() {
return phoneStandby;
}
public void setPhoneStandby(String phoneStandby) {
this.phoneStandby = phoneStandby == null ? null : phoneStandby.trim();
}
public String getPhoneEmergency() {
return phoneEmergency;
}
public void setPhoneEmergency(String phoneEmergency) {
this.phoneEmergency = phoneEmergency == null ? null : phoneEmergency.trim();
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email == null ? null : email.trim();
}
public String getResidentialAddress() {
return residentialAddress;
}
public void setResidentialAddress(String residentialAddress) {
this.residentialAddress = residentialAddress == null ? null : residentialAddress.trim();
}
public Date getLastLoginDate() {
return lastLoginDate;
}
public void setLastLoginDate(Date lastLoginDate) {
this.lastLoginDate = lastLoginDate;
}
public Date getLastLogoutDate() {
return lastLogoutDate;
}
public void setLastLogoutDate(Date lastLogoutDate) {
this.lastLogoutDate = lastLogoutDate;
}
}
通过遍历json的方式创建对象,或者通过工具直接将json转化成对象的形式。
有了对象,有了数据,就可以放入到数据库中了。不知道你用的是jdbc还是什么ssm,ssh框架,其他地方有具体的实现哦
发一个http请求过去,带上参数就可以了,和我们在浏览器上访问资源是一样的 只是它返回的是json格式的数据而已
下面给你两个方法,
public static String do_post(String url, List name_value_pair) throws IOException {
String body = "{}";
DefaultHttpClient httpclient = new DefaultHttpClient();
try {
HttpPost httpost = new HttpPost(url);
httpost.setEntity(new UrlEncodedFormEntity(name_value_pair, StandardCharsets.UTF_8));
HttpResponse response = httpclient.execute(httpost);
HttpEntity entity = response.getEntity();
body = EntityUtils.toString(entity);
} finally {
httpclient.getConnectionManager().shutdown();
}
return body;
}
public static String do_get(String url) throws ClientProtocolException, IOException {
String body = "{}";
DefaultHttpClient httpclient = new DefaultHttpClient();
try {
HttpGet httpget = new HttpGet(url);
HttpResponse response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
body = EntityUtils.toString(entity);
} finally {
httpclient.getConnectionManager().shutdown();
}
return body;
}
http参考源:
https://www.teakki.com/p/57df76741201d4c1629b9055
这个接口,你得确认下是什么接口。http的,还是webservice的,还是其他的
package wzh.Http;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.Map;
public class HttpRequest {
/**
@return URL 所代表远程资源的响应结果
/
public static String sendGet(String url, String param) {
String result = "";
BufferedReader in = null;
try {
String urlNameString = url + "?" + param;
URL realUrl = new URL(urlNameString);
// 打开和URL之间的连接
URLConnection connection = realUrl.openConnection();
// 设置通用的请求属性
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.connect();
// 获取所有响应头字段
Map> map = connection.getHeaderFields();
// 遍历所有的响应头字段
for (String key : map.keySet()) {
System.out.println(key + "--->" + map.get(key));
}
// 定义 BufferedReader输入流来读取URL的响应
in = new BufferedReader(new InputStreamReader(
connection.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
System.out.println("发送GET请求出现异常!" + e);
e.printStackTrace();
}
// 使用finally块来关闭输入流
finally {
try {
if (in != null) {
in.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
return result;
}
/**
向指定 URL 发送POST方法的请求
@param url
发送请求的 URL
@param param
请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
@return 所代表远程资源的响应结果
/
public static String sendPost(String url, String param) {
PrintWriter out = null;
BufferedReader in = null;
String result = "";
try {
URL realUrl = new URL(url);
// 打开和URL之间的连接
URLConnection conn = realUrl.openConnection();
// 设置通用的请求属性
conn.setRequestProperty("accept", "/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
// 发送POST请求必须设置如下两行
conn.setDoOutput(true);
conn.setDoInput(true);
// 获取URLConnection对象对应的输出流
out = new PrintWriter(conn.getOutputStream());
// 发送请求参数
out.print(param);
// flush输出流的缓冲
out.flush();
// 定义BufferedReader输入流来读取URL的响应
in = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
System.out.println("发送 POST 请求出现异常!"+e);
e.printStackTrace();
}
//使用finally块来关闭输出流、输入流
finally{
try{
if(out!=null){
out.close();
}
if(in!=null){
in.close();
}
}
catch(IOException ex){
ex.printStackTrace();
}
}
return result;
}
}
调用方法:
public static void main(String[] args) {
//发送 GET 请求
String s=HttpRequest.sendGet("http://localhost:6144/Home/RequestString", "key=123&v=456");
System.out.println(s);
//发送 POST 请求
String sr=HttpRequest.sendPost("http://localhost:6144/Home/RequestPostString", "key=123&v=456");
System.out.println(sr);
}
可以通过浏览器调用或者使用火狐插件模拟post请求去调取接口,得到数据后将数据处理就可以了。
基本思路,根据你的API路径,已经参数,去调用
返回给你的json数据
然后根据json的数据的类型建立自己的bean,或者数组,集合等等。
使用Gson转换json成你自己定义的类型,很容易实现的,只需要导入一个Gson jar包就可以。
具体的教程去看网上教程,很详细的。
参考: