進都進來了點個贊再走唄!
你總說總有一天我要幹嘛幹嘛,說的好像那天真會來一樣。
簡單介紹HttpClient調用接口的使用
第一步:定義HttpClientUtils類,配置連接時間和讀取時間限制
public class HttpClientUtils(){
// 設置連接超時時間
private int connectTime = 5000;
public int getConnectTime() {
return connectTime;
}
public void setConnectTime(int connectTime) {
this.connectTime = connectTime;
}
// 設置讀取超時時間
private int readTime = 1000;
public int getReadTime() {
return readTime;
}
public void setReadTime(int readTime) {
this.readTime = readTime;
}
/**
* 創建 HTTP client
* @return 實例
*/
public HttpClient createHttpClient() {
HttpClient client = new HttpClient();
client.getHttpConnectionManager().getParams()
.setConnectionTimeout(connectTime);
client.getHttpConnectionManager().getParams().setSoTimeout(readTime);
return client;
}
}
第二部:我們定義一個調用接口所需要傳的參數類,這邊我就以學生類來舉個例子
public class Stu {
//主鍵id
private String id;
//學號
private String code;
//姓名
private String name;
//年齡
private int age;
//年級
private String grade;
public String getId() {
return id;
}
public String getCode() {
return code;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public String getGrade() {
return grade;
}
public void setId(String id) {
this.id = id;
}
public void setCode(String code) {
this.code = code;
}
public void setName(String name) {
this.name = name;
}
public void setAge(int age) {
this.age = age;
}
public void setGrade(String grade) {
this.grade = grade;
}
public String toStringStu() {
return "id=" + id + "&code=" + code + "&name=" + name + "&age=" + age + "&grade=" + grade;
}
}
第三部:我們來寫一下實際調用情況,在此我就當在controller層作調用,實際我們可以將調用寫在service服務層
,實際調用可分爲以下兩種情況:
1.當調用接口所傳參數爲對象時,如下圖(此處爲你所要調用的接口案例,即代碼塊中url
,別弄錯啦!):
下面上代碼塊:
這裏時
@Qualifier
易懂例子 https://blog.csdn.net/zhizhuodewo6/article/details/81365695
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.ibm.CORBA.iiop.Request;
import com.techown.aia.ccc.service.impl.CccServiceImpl;
import com.techown.aia.utils.HttpUtils;
import net.sf.json.JSONObject;
public class StuController {
protected Logger logger = LoggerFactory.getLogger(StuController.class);
@Autowired
@Qualifier("httpUtils") //若多個接口調用,保證其唯一性
private HttpClientUtils httpUtils;
public HttpClientUtils getHttpUtils() {
return httpUtils;
}
public void setHttpUtils(HttpClientUtils httpUtils) {
this.httpUtils = httpUtils;
}
@RequestMapping("/stuHttpCliet1")
@ResponseBody
public String stuClient(Stu stu){
List<Stu> stulist=new ArrayList<Stu>();
Map<String, List<Stu>> map=new HashMap<String, List<Stu>>();
//這裏寫死數據,實際以前端傳值爲主
stu.setId("1");
stu.setCode("1001");
stu.setName("張三");
stu.setAge(20);
stu.setGrade("大一");
stulist.add(stu);
map.put("list",stulist);
String request=StringUtils.strip(map.get("list").toString(),"[]");
HttpClient client=httpUtils.createHttpClient();
String response="";
//若調用接口類似於此類url
String url="http://localhost:9080/stuClient";
try {
PostMethod post=new PostMethod(url);
post.setRequestEntity(new StringRequestEntity(request, "text/html", "UTF-8"));
post.setRequestHeader("content-type", "text/html");
HttpMethodParams params = post.getParams();
params.setContentCharset("UTF-8");
int status=client.executeMethod(post);
//status爲200時,調用成功
if (status == HttpStatus.SC_OK) {
response = post.getResponseBodyAsString();
JSONObject jsonObject=JSONObject.fromObject(response);
System.out.print(jsonObject);
}
} catch (Exception e) {
logger.error("error {}",e.getMessage());
}
return null;
}
}
2.當調用接口所傳參數爲攜帶參數時,如下圖(此處爲你所要調用的接口案例,即代碼塊中url
,別弄錯啦!):
下面上代碼塊(放同一Controller類中):
@RequestMapping("/stuHttpCliet2")
@ResponseBody
public String stuClientp(Stu stup) throws UnsupportedEncodingException{
//這裏寫死數據,實際以前端傳值爲主
stup.setId("1");
stup.setCode("1001");
stup.setName("張三");
stup.setAge(20);
stup.setGrade("大一");
HttpClient client=httpUtils.createHttpClient();
String response="";
//若調用接口類似於此類url
String url="http://localhost:9080/stuClient?id=&code=&name=&age=&grade=";
String url2="http://localhost:9080/stuClient";
String requestParam=stup.toStringStu();
//此處爲正常調用
//String request=url2+"?"+requestParam;
//此處所傳五個參數中不能有空格, 類似於這種 code='YY NN '或name='張三',
//否則要對參數進行編碼,即URLEncoder.encode(code,'UTF-8')或URLEncoder.encode(name,'UTF-8'),對上面寫死參數以下寫法
String request=url2+"?"+"id="+stup.getId()+"&code="+stup.getCode()+"&name="+URLEncoder.encode(stup.getName(),"UTF-8")
+"&age="+stup.getAge()+"&grade="+URLEncoder.encode(stup.getGrade(), "UTF-8");
try {
PostMethod post=new PostMethod(url2);
post.setRequestEntity(new StringRequestEntity(request, "text/html", "UTF-8"));
post.setRequestHeader("content-type", "text/html");
HttpMethodParams params = post.getParams();
params.setContentCharset("UTF-8");
int status=client.executeMethod(post);
//status爲200時,調用成功
if (status == HttpStatus.SC_OK) {
response = post.getResponseBodyAsString();
JSONObject jsonObject=JSONObject.fromObject(response);
System.out.print(jsonObject);
}
} catch (Exception e) {
logger.error("error {}",e.getMessage());
}
return null;
}
整理不易,希望對進來的小夥伴們有幫助哈!
臨走再送一句毒雞湯給你們,努力不一定成功,但不努力一定很輕鬆。