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
}

私のクライアントの 1 人が、APN 設定でプロキシを設定した直後に IllegalArgumentException があると私に言ったので、それで問題ないかどうかはよくわかりません。

4

1 に答える 1

1

このように、ホスト API_REST_HOST への実際の呼び出しを行う executeRequest と呼ばれる 1 つのメソッドを使用します (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 に答える