0

我从来没有真正在 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);

我不确定问题是什么,任何见解都会有所帮助。

4

1 回答 1

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没有连接(因为它被卡住了),您还应该考虑为什么会发生这种情况(也许您需要配置代理?)

于 2013-07-10T18:49:42.763 回答