利用代理模式是解决ajax跨域问题的一种简单有效的途径,在这里,利用apache的组件HttpComponents(http://hc.apache.org/ ),利用下面的方法,传参为第三方服务的url,则返回响应字符串
1 public static String getHttpString(String url) { 2 HttpClient client = new DefaultHttpClient(); 3 try { 4 HttpGet httpGet = new HttpGet(url); 5 HttpResponse response = client.execute(httpGet); 6 7 if(response.getStatusLine().getStatusCode() == 200) { 8 InputStream is = response.getEntity().getContent(); 9 BufferedReader br = new BufferedReader(new InputStreamReader(is)); 10 StringBuffer sb = new StringBuffer(); 11 String str = null; 12 while((str = br.readLine()) != null) { 13 sb.append(str); 14 } 15 br.close(); 16 return sb.toString(); 17 } else { 18 System.out.println("错误代码:" + response.getStatusLine().getStatusCode()); 19 } 20 } catch (Exception e) { 21 e.printStackTrace(); 22 } finally{ 23 if(client != null) { 24 client.getConnectionManager().shutdown(); 25 } 26 } 27 return null; 28 }