java中使用HttpClient实现服务端跨域
一、 准备jar包
1、httpclient-4.5.3.jar
2、httpcore-4.4.8.jar
二、HttpClient 执行 get 请求 后台代码
/** * @description: 使用httpClient对象执行get请求 * @param: uri 需要跨域请求的uri * @author:wu * @throws IOException * @throws ClientProtocolException * @createDate:2018年2月28日 下午2:19:00 */ public static String doGet(String uri) throws ClientProtocolException, IOException{ if(StringUtils.isBlank(uri)){ uri="http://192.168.1.253:999/paseJson/cityJson"; } // 1、 创建 httpClient 对象 CloseableHttpClient httpClient = HttpClients.createDefault(); // 2、 创建 get 对象 HttpGet get =new HttpGet(uri); // 3、 执行 get 请求 CloseableHttpResponse response = httpClient.execute(get); // 4、 获取返回结果 HttpEntity 对象 HttpEntity entity = response.getEntity(); // 5、获取返回结果中的数据 String data = EntityUtils.toString(entity); // 6、 关闭 response、 关闭 httpClient response.close(); httpClient.close(); return data; }
三、 HttpClient 执行 post 请求 后台代码
/** * @description:使用httpClient对象执行 post 请求 * @param: uri 需要跨域请求的uri , formDataMap 模拟表单需要提交数据 (name - value 形式) * @author:wu * @createDate:2018年2月28日 下午4:36:55 */ public static String doPost(String uri,Map<String,Object> formDataMap) throws ClientProtocolException, IOException{ if(StringUtils.isBlank(uri)){ uri="http://192.168.1.253:999/paseJson/cityJson"; } // 1、创建httpClient 对象 CloseableHttpClient httpClient = HttpClients.createDefault(); // 2、 创建post 对象 HttpPost post =new HttpPost(uri); // 3、 创建一个list形式数据,模拟提交表单。 List<NameValuePair> formDataList=new ArrayList<>(); // TODO: 这里可以遍历模拟表单传递过来的数据 formDataMap /*Iterator<Entry<String, Object>> iterator = formDataMap.entrySet().iterator(); while(iterator.hasNext()){ Entry<String, Object> next = iterator.next(); String key = next.getKey(); String value = next.getValue().toString(); formDataList.add(new BasicNameValuePair(key, value)); }*/ formDataList.add(new BasicNameValuePair("ids", "110")); formDataList.add(new BasicNameValuePair("name", "httpClient 请求数据")); // 4、 把表单数据包装到entity 对象中 (StringEntity) StringEntity formData = new UrlEncodedFormEntity(formDataList, "UTF-8"); post.setEntity(formData); // 5、 执行post请求 CloseableHttpResponse response = httpClient.execute(post); // 6、 获取响应数据 HttpEntity entity = response.getEntity(); // 7、 响应数据转换为字符串 String data = EntityUtils.toString(entity); // 8、 关闭 httpClient对象、关闭 response response.close(); httpClient.close(); return data; }
四、 测试代码
public static void main(String[] args) throws ClientProtocolException, IOException { String data=""; //data = doGet("http://192.168.1.253:999/paseJson/cityJson"); data= doPost("https://www.baidu.com/", null); System.out.println(data); }
五、源码附件
不知道怎么上传。。
(关于跨域的详细理解,请参考这篇文章: http://blog.csdn.net/HaHa_Sir/article/details/79390893)