1、首先加上依赖包
<dependencies>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.2</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.28</version>
</dependency>
</dependencies>
2、干货代码
工具持久类Utils
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.HTTP;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
public class Utils {
static CloseableHttpClient client = HttpClients.createDefault();
public static void operation(String function,JSONObject jo){
//设置请求的网址
System.out.println(sendPost(jo, "http://10.74.25.53:8081/" + function));
}
public static String sendPost(JSONObject json, String URL) {
HttpPost post = new HttpPost(URL);
post.setHeader("Content-Type", "application/json");
post.addHeader("Authorization", "Basic YWRtaW46");
String result;
try {
StringEntity s = new StringEntity(json.toString(), "utf-8");
s.setContentType(new BasicHeader(HTTP.CONTENT_TYPE,
"application/json"));
post.setEntity(s);
// 发送请求
HttpResponse httpResponse = client.execute(post);
// 获取响应输入流
InputStream inStream = httpResponse.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(
inStream, "utf-8"));
StringBuilder strber = new StringBuilder();
String line;
while ((line = reader.readLine()) != null)
strber.append(line + "\n");
inStream.close();
result = strber.toString();
if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
System.out.println("success");
} else {
System.out.println("failed");
}
} catch (Exception e) {
throw new RuntimeException(e);
}
return result;
}
}
测试类
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
public class SendRequest {
public static void main(String[] args) {
JSONObject jo = new JSONObject();
//设置表名
jo.put("table", "A_Entname");
//放数据
JSONArray ja = new JSONArray();
ja.add(0, "11");
ja.add(1, "22");
ja.add(2, "33");
ja.add(3, "44");
ja.add(4, "55");
ja.add(5, "66");
jo.put("data",ja);
Utils utils=new Utils();
utils.operation("setData",jo);
JSONObject jo2 = new JSONObject();
//设置表名
jo2.put("table", "A_Entname");
//放数据
JSONArray ja2 = new JSONArray();
ja2.add(0, "11");
jo2.put("data",ja2);
utils.operation("getData",jo2);
utils.operation("deleteData",jo2);
utils.operation("getData",jo2);
}
}