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;
}
}
如果出現請求頭不對的情況,可以把藍色那段換成下面的
StringEntity sentity = new StringEntity(JSON.toJSONString(fkLogin), ContentType.APPLICATION_JSON);
httpPost.setEntity(sentity);
需要設置header的話用httpPost.setHeader()就行了
