我正在尝试测试几个API并进行比较。 对于其中一个其他服务,我只能在输入请求时得到响应 在浏览器中。 当我从代码(带有泽西岛的Java)发送具有完全相同URL的请求时,我得到401未授权。
作为一种解决方法,出于好奇,我想让我的java客户端发送 请求好像它是一个浏览器,所以我可以轻松地测试响应。
这纯粹是为了进行基准测试......我知道这不是一个强大的解决方案。
我获取请求的代码:
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
public class ClientTest
{
@Test
public void testGisGraphy()
{
String url = "http://services.gisgraphy.com/geocoding/geocode?address=89%20Rue%20Champoiseau%2C%20Tours&country=FR&format=JSON&postal=true";
Client client = Client.create();
WebResource webResource = client.resource(url);
ClientResponse response = webResource.accept("application/json").get(ClientResponse.class);
String jsonString = response.getEntity(String.class);
System.out.println(jsonString.toString());
}
}
答案 0 :(得分:1)
以下工作。
两个标题,"接受编码" ,其值为" gzip" 和" Accept-Language&#34 ; 需要任何仲裁值。接受使用值gzip进行编码是必须的。接受任何仲裁值的语言都没问题。
public static void main(String[] args) {
String url =
"http://services.gisgraphy.com/geocoding/geocode?address=89%20Rue%20Champoiseau%2C%20Tours&country=FR&format=JSON&postal=true";
Client client = Client.create();
WebResource webResource = client.resource(url);
ClientResponse response =
webResource
.accept("application/json")
.header("Accept-Encoding","gzip")
.header("Accept-Language", "arbit text")
.get(ClientResponse.class);
String jsonString = response.getEntity(String.class);
System.out.println(jsonString.toString());
}
我试着连续运行它。以下是回复:
<html>
<head>
<title>Too much requests</title>
<style>
body { font-family: Tahoma, Verdana, Arial, sans-serif; }
</style>
</head>
<body bgcolor="white" text="black">
<table width="100%" height="100%">
<tr>
<td align="center" valigin="middle">
Your request can not be processed :
<ul>
<li>Are you a bot or do you use those webservices in a software ? you can only use the webservice in a browser</li>
<li>Do you reach the maximum number of requests / seconds allowed</li>
</ul>
<br/><br/>
Wait a little bit and resubmit your request
</br></br/>
If you want to have better QOS and SLA, you can <a href="http://premium.gisgraphy.com/">subscribe to premium webservices</a>
</td>
</tr>
</table>
</body>
</html>
&#13;
结论: - 在服务器端,他们正在进行一些检查,以便只有来自浏览器的请求得到服务,而其余的未经授权。
进行反复试验,似乎是请求标题&#34; Accept-Encoding&#34;和#34;接受语言&#34;必须在请求中。
答案 1 :(得分:0)
您应指定用户代理标头