最近学习小程序,网上找了个经典案例,就是请求豆瓣api的,但是豆瓣好像拉黑小程序了,访问不了,会报403错误,下面是解决方案
首先在开发工具上勾选下面:
方案1
网上说把网址替换了,这个可以解决,但是请求到的结果是不一样的
https://api.douban.com/v2/movie/top250 官网请求到的结果如下图:是有title和小图之类的
而 http://t.yushu.im/v2/movie/top250 请求的结果如下:
所以这个不是最好的解决办法,下面搭建Nginx代理解决
方案2
nginx 官网下载地址:http://nginx.org/en/download.html
本人用的是window版本,其他版本的自行百度解决,下载后解压出来放到一个目录下,本人放在Program Files目录下:
进入conf下找到nginx.conf,然后配置一下,在 server {}代码快中加入下面代码:
location /v2/ {
proxy_store off;
proxy_redirect off;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header Referer 'no-referrer-when-downgrade';
proxy_set_header User-Agent 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36';
proxy_connect_timeout 600;
proxy_read_timeout 600;
proxy_send_timeout 600;
proxy_pass https://api.douban.com/v2/;
}
保存然后启动Nginx,下面是启动命令
启动后在浏览器输入 http://localhost
即可访问到下面结果:
接下面在小程序里把 https://api.douban.com/v2/movie/top250 改成
http://localhost/v2/movie/top250
注意一点,这里的header设置是’content-type’: ‘application/xml’
方案3
java后台替代方案,自己搭建一个java服务端,转发请求,获取数据再返回,本人用的是springmvc,springmvc详细搭建请看我另一篇博客:
https://blog.csdn.net/u014204541/article/details/79273173
下面是核心代码:
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
@RequestMapping("/testController")
public class TestController {
@RequestMapping(params = "tip")
@ResponseBody
public void datagridTotal(HttpServletRequest request, HttpServletResponse response) throws IOException{
String url = request.getParameter("douban");//获取拼接的参数
System.out.println("url:"+url);//拼接豆瓣的地址
String douban_url = "https://api.douban.com/" + url;
String result = sendPost(douban_url,"");
System.out.println(result);
response.getWriter().print(result);
}
/**
* 发送http POST请求
*
* @param
* @return 远程响应结果
*/
public static String sendPost(String u, String json) {
StringBuffer sbf = new StringBuffer();
try {
URL url = new URL(u);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setUseCaches(false);
connection.setInstanceFollowRedirects(true);
connection.addRequestProperty("role", "Admin");
connection.addRequestProperty("Content-Type", "application/xml");//注意,这里也是xml
connection.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
connection.connect();
DataOutputStream out = new DataOutputStream(connection.getOutputStream());
if (!"".equals(json)) {
out.writeBytes(json);
}
out.flush();
out.close();
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String lines;
while ((lines = reader.readLine()) != null) {
lines = new String(lines.getBytes(), "utf-8");
sbf.append(lines);
}
System.out.println(sbf);
reader.close();
// 断开连接
connection.disconnect();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return sbf.toString();
}
}
微信端地址修改为以下:
访问结果还是一样的
方案4
搭建node.js服务器端
node.js详情搭建请参考我另一篇博客:
https://blog.csdn.net/u014204541/article/details/80092750
下面是node.js搭建后的代码,保存到一个文件里,我的文件叫douban.js
var http = require('http')
var request = require('request')
// 1. 创建 Server
var server = http.createServer()
server.on('request', function (req, res) {
res.writeHead(200,{'Content-Type':'application/json;charset=utf-8'});//设置response编码为utf-8
var url = req.url
console.log("url:"+url);
//发送请求豆瓣获取json数据
request({
url: "https://api.douban.com/"+url,
method: "POST",
json: true,
headers: {
"content-type": "application/xml",
},
body: ""
}, function(error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body) // 请求成功的处理逻辑
res.write(JSON.stringify(body))
res.end()
}
});
})
// 3. 绑定端口号,启动服务
server.listen(3000, function () {
console.log('running...')
})
启动nodejs后,通过浏览器访问结果返回
微信小程序端代码改成以下: