我从来没有真正在Java中使用过http请求,我正在尝试创建一个基本上会重新创建此http://supersecretserver.net:8080/http://whateverwebsite.com的请求 该服务器采用任何网站,只返回响应正文中页面的文本。
代码如下:
public String getText(String webPage) throws ParseException, IOException{
HttpResponse response = null;
try {
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet();
request.setURI(new URI("http://supersecretserver.net:8080/" + "http://www.androidhive.info/2012/01/android-text-to-speech-tutorial/"));
response = client.execute(request);
} catch (URISyntaxException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String responseBody = "No text found on webpage.";
int responseCode = response.getStatusLine().getStatusCode();
switch(responseCode) {
case 200:
HttpEntity entity = response.getEntity();
if(entity != null) {
responseBody = EntityUtils.toString(entity);
}
}
System.out.println("Returning Response..");
System.out.println(responseBody);
return responseBody;
}
似乎陷入了
response = client.execute(request);
我不确定问题是什么,任何见解都会有所帮助。
答案 0 :(得分:1)
看起来您的HttpClient可能没有超时,您可以通过以下示例设置超时值(来自http://www.jayway.com/2009/03/17/configuring-timeout-with-apache-httpclient-40/)
您只需要考虑一个对您有意义的超时值。
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpParams params = httpClient.getParams();
HttpConnectionParams.setConnectionTimeout(httpParams, connectionTimeoutMillis);
HttpConnectionParams.setSoTimeout(httpParams, socketTimeoutMillis);
此外,由于您的HttpClient没有连接(因为它已经卡住),您还应该考虑为什么会发生这种情况(也许您需要配置代理?)