获取微信公众号accessToken需要服务器ip配置白名单,但部分客户服务器没有固定ip,因而经常会出现因为ip白名单问题而获取不到公众号的accessToken。
解决办法:proxy代理
public String sendGet(String url, String param) { String result = ""; BufferedReader in = null; try { String urlNameString = url + "?" + param; URL realUrl = new URL(urlNameString); //proxy代理服务 String host = "www.baidu.com";//代理服务器域名 String port = "8080";//端口号 //InetAddress.getByName(host),通过域名获得ip地址 InetSocketAddress socketAddress = new InetSocketAddress(InetAddress.getByName(host), port); Proxy proxy = new Proxy(Proxy.Type.HTTP,socketAddress); // 打开和URL之间的连接 URLConnection conn = realUrl.openConnection(); if (proxy != null) { conn = realUrl.openConnection(proxy); } // 设置通用的请求属性 conn.setRequestProperty("accept", "*/*"); conn.setRequestProperty("connection", "Keep-Alive"); conn.setRequestProperty("Charset", "utf-8"); conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)"); // 建立实际的连接 conn.connect(); // 获取所有响应头字段 Map<String, List<String>> map = conn.getHeaderFields(); /* * // 遍历所有的响应头字段 for (String key : map.keySet()) { log.debug(key + * "--->" + map.get(key)); } */ // 定义 BufferedReader输入流来读取URL的响应 // out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8"); in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8")); String line; while ((line = in.readLine()) != null) { result += line; } } catch (Exception e) { log.debug("发送GET请求失败:" + ExceptionHelper.GetErrInfo(e)); } // 使用finally块来关闭输入流 finally { try { if (in != null) { in.close(); } } catch (Exception e2) { log.info(e2.getMessage()); } } return result; }
补充:
407 Proxy Authentication Required
与401响应类似,只不过客户端必须在代理服务器上进行身份验证。代理服务器必须返回一个 Proxy-Authenticate 用以进行身份询问。客户端可以返回一个 Proxy-Authorization 信息头用以验证。参见RFC 2617。
If your proxy requires authentication it will give you response 407. In this case you‘ll need the following code: Authenticator authenticator = new Authenticator() { public PasswordAuthentication getPasswordAuthentication() { return (new PasswordAuthentication("user", "password".toCharArray())); } }; Authenticator.setDefault(authenticator);
原文地址:https://www.cnblogs.com/TSHHENLIHAI/p/10826441.html
时间: 2024-11-07 11:41:35