import java.util.ArrayList; import java.util.List; import java.util.Map; import org.apache.http.HttpEntity; import org.apache.http.NameValuePair; import org.apache.http.StatusLine; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.message.BasicNameValuePair; import org.apache.http.util.EntityUtils; import org.springframework.data.repository.query.QueryMethod; import com.alibaba.fastjson.JSON; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.flatform.fklc.domain.FkLogin; import java.io.IOException; public class EntityZDUtil { //连接的网址,这里假装一个 private static final String SERVICE_URL = "http://192.122.91.111:8080/test/tester/tttest.do"; //方法 public static String Test() { CloseableHttpClient httpClient = HttpClients.createDefault(); try { HttpPost httpPost = new HttpPost(SERVICE_URL); List<NameValuePair> nvps = new ArrayList<NameValuePair>(); //根据需要传输的参数建立实体FkLogin //需要的数据格式为 data={ "uname": "admin", "upwd": "12345" } FkLogin fkLogin = new FkLogin(); fkLogin.setUname("admin"); fkLogin.setUpwd("12345"); //将实体(List之类的也行)转化为Json传过去 nvps.add(new BasicNameValuePair("data", JSON.toJSONString(fkLogin))); httpPost.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8")); CloseableHttpResponse response = httpClient.execute(httpPost); try { StatusLine statusLine = response.getStatusLine(); int statusCode = statusLine.getStatusCode(); //200为请求成功(只是请求成功,如进行查询,连上了,查询失败也是200,具体成功与否看返回的数据) if (statusCode == 200) { //获取返回值 HttpEntity entity = response.getEntity(); String mes = EntityUtils.toString(entity, "UTF-8"); return mes; } else { return null; } } catch (Exception e) { e.printStackTrace(); } finally { response.close(); } } catch (Exception e) { e.printStackTrace(); } return null; } }
java后台调用接口并获取返回值
最新推荐文章于 2024-05-13 20:31:06 发布