Android:无法在防火墙后面发出http请求

时间:2010-03-29 16:43:19

标签: android firewall http-proxy

当没有防火墙时,标准getUrlContent工作正常。但是当我尝试在防火墙后面进行操作时,我得到了例外。

我试过在AVD管理器中设置“http代理服务器”,但它没有用。知道如何正确设置吗?

和btw:来自android文档“你可以使用-verbose-proxy选项来诊断代理连接问题。” -verbose-proxy根本不是一个有效的选项。

protected static synchronized String getUrlContent(String url) throws ApiException {
    if(url.equals("try")){
        return "thanks";

    }
    if (sUserAgent == null) {
        throw new ApiException("User-Agent string must be prepared");
    }

    // Create client and set our specific user-agent string
    HttpClient client = new DefaultHttpClient();
    HttpGet request = new HttpGet(url);
    request.setHeader("User-Agent", sUserAgent);

    try {
        HttpResponse response = client.execute(request);

        // Check if server response is valid
        StatusLine status = response.getStatusLine();
        if (status.getStatusCode() != HTTP_STATUS_OK) {
            throw new ApiException("Invalid response from server: " +
                    status.toString());
        }

        // Pull content stream from response
        HttpEntity entity = response.getEntity();
        InputStream inputStream = entity.getContent();

        ByteArrayOutputStream content = new ByteArrayOutputStream();

        // Read response into a buffered stream
        int readBytes = 0;
        while ((readBytes = inputStream.read(sBuffer)) != -1) {
            content.write(sBuffer, 0, readBytes);
        }

        // Return result from buffered stream
        return new String(content.toByteArray());
    } catch (IOException e) {
        throw new ApiException("Problem communicating with API", e);
    }
}

2 个答案:

答案 0 :(得分:5)

您也可以在代码中设置代理。

   public void setProxy(DefaultHttpClient httpclient) {  
           final String PROXY_IP = "<insert your IP here>";  
            final int PROXY_PORT = <insert_PROXY_PORT#>;  

            httpclient.getCredentialsProvider().setCredentials(  
                    new AuthScope(PROXY_IP, PROXY_PORT),  
                    new UsernamePasswordCredentials(  
                            "username", "password"));  

           HttpHost proxy = new HttpHost(PROXY_IP, PROXY_PORT);  

           httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY,  
                   proxy);  


       }  

答案 1 :(得分:0)

看看这个小小的野兽是否会对你有所帮助。您可能需要在正在运行的仿真器映像中使用它。

http://openhandsetmagazine.com/2007/11/tips-howto-connect-android-emulator-behind-proxy/