公司JSF项目最早的注释时间为2008年。非常老而且稳定的项目需要使用Post请求来进行外部接口的调用,遇到了很多问题。
第一次尝试:
直接在项目中书写http请求代码。网上粘贴出的代码,脱敏后
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URI;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
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.BasicNameValuePair;
import net.sf.json.JSONObject;
public class contect_flask {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
JSONObject jsonObject1= new JSONObject();//post传递的参数
infoJson.put("name", "value");
System.out.println("最终获得的信息为=" + post(jsonObject1,"http://255.255.255.1"));
}
public static String post(JSONObject json, String url){
String result = "";
HttpPost post = new HttpPost(url);
try{
CloseableHttpClient httpClient = HttpClients.createDefault();
post.setHeader("Content-Type","application/json;charset=utf-8");
post.addHeader("Authorization", "Basic YWRtaW46");
StringEntity postingString = new StringEntity(json.toString(),"utf-8");
post.setEntity(postingString);
//添加连接超时和相应超时设置
RequestConfig requestConfig = RequestConfig.custom()
.setConnectTimeout(5000)
.setConnectionRequestTimeout(1000)
.setSocketTimeout(5000).build();
post.setConfig(requestConfig);
HttpResponse response = httpClient.execute(post);
InputStream in = response.getEntity().getContent();
BufferedReader br = new BufferedReader(new InputStreamReader(in, "utf-8"));
StringBuilder strber= new StringBuilder();
String line = null;
while((line = br.readLine())!=null){
strber.append(line+'\n');
}
br.close();
in.close();
result = strber.toString();
if(response.getStatusLine().getStatusCode()!=HttpStatus.SC_OK){
result = "服务器异常";
}
} catch (Exception e){
System.out.println("请求异常");
throw new RuntimeException(e);
} finally{
post.abort();
}
// HttpClient client = new DefaultHttpClient();
// HttpPost post = new HttpPost(testUrl);
//
// PostMethod postMethod = new PostMethod(testUrl);
// // 必须设置下面这个Header
// postMethod.addRequestHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.81 Safari/537.36");
// String toJson = infoJson.toString();
// try {
// RequestEntity se = new StringRequestEntity(toJson ,"application/json" ,"UTF-8");
// postMethod.setRequestEntity(se);
// postMethod.setRequestHeader("Content-Type","application/json");
// //默认的重试策略
// postMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());
// postMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 5000);//设置超时时间
// int httpStatus = client.ex
// String str=postMethod.getResponseBodyAsString();
// T.console("str-------:"+str);
// } catch (UnsupportedEncodingException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
return result;
}
}
实测此方法有效。需要完整的导入如下jar包。
httpclient-4.5.2.jar
httpcore-4.4.10.jar
commons-beanutils-1.9.3.jar
commons-collections-3.2.1.jar
commons-lang-2.6.jar
commons-logging-1.2.jar
ezmorph-1.0.6.jar
json-lib-2.4-jdk15.jar
包的导入必须完整,如果有缺失,回报错。
但是将代码放入JSF项目中,在post.setHeader post.addHeader报错误,说找不到方法,查明原因是因为项目中的httpclient的jar报版本太低,没有此类方法。若跟新项目和jar,会导致多台主机项目需要重新部署jar包,代价较大。所以没有用这个方法
第二次尝试
不能使用java的方法就得使用JSF自带的。计划在jsp页面中书写类似于jQuery的ajax方法来进行外部url接口的访问。但是由于jsf的post请求是请求后台代码的Bean的,不是用来请求外部网址的接口。所以没有继续研究下去。
JSF为我们提供了标签类的前台请求。
<f:metadata>
<f:viewParam name="data" value="#{bean.data}" />
<f:event type="preRenderView" listener="#{bean.process}" />
</f:metadata>
public void process() throws IOException {
String message = "Hello! You have sent the following data: " + data;
String json = new Gson().toJson(Collections.singletonMap("message", message));
FacesContext context = FacesContext.getCurrentInstance();
ExternalContext ec = context.getExternalContext();
ec.setResponseContentType("application/json");
ec.setResponseCharacterEncoding("UTF-8");
ec.getResponseOutputWriter().write(json);
context.responseComplete(); // Prevent JSF from rendering the view.
}
路径:http://www.it1352.com/48626.html
https://www.w3cschool.cn/java/jsf-ajax-helloworld.html
第三次尝试:
在《Java调用第三方http接口的方式》中找到了一种适用老版项目,不需要导入jar包的。通过JDK网络类Java.net.HttpURLConnection,比较原始,但是适合大多数java项目。
https://blog.csdn.net/zengqingshanzheng/article/details/95946252