我试图通过更改我的连接中的用户代理属性来“欺骗”Google财经以为我是一个网络浏览器。但是,当我使用实际的Web浏览器时,我得到的响应仍然不是我应该得到的。我想知道为什么会这样,以及我需要做些什么来使它工作?以下是相关代码(“网站”为https://www.google.co.uk/finance/converter?a=1&from=GBP&to=USD):
protected static String readURL(String site) {
StringBuilder buff = new StringBuilder();
try {
HttpURLConnection conn = (HttpURLConnection) new URL(site).openConnection();
conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.79 Safari/537.36 Edge/14.14393");
conn.connect();
BufferedReader bfr = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String inputLine;
while ((inputLine = bfr.readLine()) != null)
buff.append(inputLine).append('\n');
bfr.close();
}
catch (Exception ioe) {
System.err.println("Failed to read from \""+site+"\": "+ioe.getMessage());
}
return buff.toString();
}
编辑:我应该注意到这是在Android应用程序中,而不是Java应用程序。它也不会在WebView或其他任何内容中显示给用户,这在后台发生。
答案 0 :(得分:0)
webform似乎表现正常,没有与用户代理混淆。此改进请求返回有效响应:
D/TAG: currency_converter_result>5 GBP = <span class=bld>6.3645 USD
改装请求:
final Map<String,String> fieldMap = new HashMap<>();
fieldMap.put("a","5");
fieldMap.put("from","GBP");
fieldMap.put("to","USD");
RequestBody requestBody = RequestBody.create(MediaType.parse("text/plain"), "");
final Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://www.google.co.uk")
.build();
final ConversionService wService = retrofit.create(ConversionService.class);
Call<ResponseBody> data = wService.convertCurrency(fieldMap);
data.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
String resp = "";
if ( response.body() != null ) {
try {
resp = response.body().string();
int index = resp.indexOf("currency_converter_result" );
int end = resp.indexOf("</span>", index );
String result = resp.substring(index, end);
Log.d("TAG", result);
} catch ( IOException e) {
}
}
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
Log.e(TAG,"Failure");
}
});
}
ConversionService.java
public interface ConversionService {
@GET("/finance/converter")
Call<ResponseBody> convertCurrency(@QueryMap Map<String,String> queryMap);
}