0

这是建立 HTTP 连接的最佳方式。我的意思是使用代理等等。现在我正在使用这个:

StringBuilder entity = new StringBuilder();
entity.append("request body");

AndroidHttpClient httpClient = AndroidHttpClient.newInstance(null);

String proxyHost = android.net.Proxy.getDefaultHost();
int proxyPort = android.net.Proxy.getDefaultPort();
if (proxyHost != null && proxyPort > 0) {
    HttpHost proxy = new HttpHost(proxyHost, proxyPort);
    ConnRouteParams.setDefaultProxy(httpClient.getParams(), proxy);
}
HttpPost httpPost = new HttpPost("https://w.qiwi.ru/term2/xmlutf.jsp");
httpPost.setEntity(new StringEntity(entity.toString(), "UTF-8"));
httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");
HttpParams params = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(params, 15000);
HttpConnectionParams.setSoTimeout(params, 30000);
httpPost.setParams(params);
HttpResponse httpResponse = httpClient.execute(httpPost);

int responseCode = httpResponse.getStatusLine().getStatusCode();
if (responseCode == HttpStatus.SC_OK) {
    // parsing response
}

我不确定这是否可以,因为我的一位客户告诉我,他在 APN 设置中设置代理后立即出现 IllegalArgumentException。

4

1 回答 1

1

使用一种名为 executeRequest 的方法来实际调用主机 API_REST_HOST,这种方式(API_REST_HOST 可以是 flickr 的 rest api 的“api.flickr.com”之类的值。添加了 HTTP 和端口)

 private void executeRequest(HttpGet get, ResponseHandler handler) throws IOException {
    HttpEntity entity = null;
    HttpHost host = new HttpHost(API_REST_HOST, 80, "http");
    try {
        final HttpResponse response = mClient.execute(host, get);
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            entity = response.getEntity();
            final InputStream in = entity.getContent();
            handler.handleResponse(in);
        }
    } catch (ConnectTimeoutException e) {
        throw new ConnectTimeoutException();
    } catch (ClientProtocolException e) {
        throw new ClientProtocolException();
    } catch (IOException e) {
        e.printStackTrace();
        throw new IOException();
    } 
    finally {
        if (entity != null) {
            try {
                entity.consumeContent();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

以这种方式从这里调用此 API:

final HttpGet get = new HttpGet(uri.build().toString());
    executeRequest(get, new ResponseHandler() {
        public void handleResponse(InputStream in) throws IOException {
            parseResponse(in, new ResponseParser() {
                public void parseResponse(XmlPullParser parser)
                        throws XmlPullParserException, IOException {
                    parseToken(parser, token, userId);
                }
            });
        }
    });

你的uri是这样构造的:

final Uri.Builder builder = new Uri.Builder();
builder.path(ANY_PATH_AHEAD_OF_THE_BASE_URL_IF_REQD);
builder.appendQueryParameter(PARAM_KEY, PARAM_VALUE);

您的 mClient 以这种方式声明为类级别变量

private HttpClient mClient;

最后你的 parseResponse 可以用这种方式完成(比如你想解析 XML 数据)

private void parseResponse(InputStream in, ResponseParser responseParser) throws IOException {
    final XmlPullParser parser = Xml.newPullParser();
    try {
        parser.setInput(new InputStreamReader(in));

        int type;
        while ((type = parser.next()) != XmlPullParser.START_TAG &&
                type != XmlPullParser.END_DOCUMENT) {
            // Empty
        }

        if (type != XmlPullParser.START_TAG) {
            throw new InflateException(parser.getPositionDescription()
                    + ": No start tag found!");
        }

        String name = parser.getName();
        if (RESPONSE_TAG_RSP.equals(name)) {
            final String value = parser.getAttributeValue(null, RESPONSE_ATTR_STAT);
            if (!RESPONSE_STATUS_OK.equals(value)) {
                throw new IOException("Wrong status: " + value);
            }
        }

        responseParser.parseResponse(parser);

    } catch (XmlPullParserException e) {
        final IOException ioe = new IOException("Could not parse the response");
        ioe.initCause(e);
        throw ioe;
    }
}

此代码处理所有可能的异常,并显示如何正确解析来自 HTTP 连接的输入流的响应。

如您所知,请确保您在单独的线程中而不是在 UI 线程中使用它。就是这样 :)

于 2011-09-27T12:27:44.993 回答