0

如何将变量作为指向函数的指针传递?我有以下要重构的代码

    public static HttpResponse getJSONEntityFromURL(Context context, String url) throws ClientProtocolException, IOException {
        HttpClient httpclient = new DefaultHttpClient();
        HttpGet httpget = new HttpGet(url);
        httpget.addHeader("Accept", "application/json");
        httpget.addHeader("Content-Type", "application/json; charset=UTF-8");
        HttpResponse response;

        response = httpclient.execute(httpget);
        return response;
    }

像这样

    public static HttpResponse getJSONEntityFromURL(Context context, String url) throws ClientProtocolException, IOException {
        HttpClient httpclient = new DefaultHttpClient();
        HttpGet httpget = new HttpGet(url);
            setHeaders(httpget);
        HttpResponse response;

        response = httpclient.execute(httpget);
        return response;
    }

private static void setHeaders(HttpRequestBase httpget) {
    httpget.addHeader("Accept", "application/json");
    httpget.addHeader("Content-Type", "application/json; charset=UTF-8");
}

我假设我需要将 httpget 参数作为指针传递?

4

4 回答 4

3

我假设我需要将 httpget 参数作为指针传递?

不,因为 Java 没有指针。

您那里的代码看起来不错——您正在将HttpGet对象传递setHeaders()给它并在其上调用方法。如果您当前的语法有特定问题,请解释。

于 2013-02-20T16:44:26.803 回答
1

我会用那个

private static void setHeaders(final HttpRequestBase httpget) {
  httpget.addHeader("Accept", "application/json");
  httpget.addHeader("Content-Type", "application/json; charset=UTF-8");
}

确定它不是一个指针,但在这种情况下,引用 httpget 被更改而不返回 HttpRequestBase。

于 2013-02-20T16:44:48.117 回答
1

Java 只允许你传递引用,因为 Java 不实现指针算法

All primitive types are passed by copy, and all object types are passed by ref. (By copy, but the copy of the memory address instead of duplicating the whole object.)

the way you did i believe is the correct one:

private static void setHeaders(HttpRequestBase AGet) {
    AGet.addHeader("Accept", "application/json");
    AGet.addHeader("Content-Type", "application/json; charset=UTF-8");
}

Unless you gonna need to use this method somewhere else I recommend the first code.

http://docs.oracle.com/javase/tutorial/java/javaOO/arguments.html <- documentation

于 2013-02-20T16:47:49.397 回答
1

You can use the HttpMessage interface as seen below: -

http://developer.android.com/reference/org/apache/http/HttpMessage.html

This will allow you to accept an implementation of this interface, i.e. an instance of HttpGet

i.e: -

private static void setHeaders(HttpMessage httpMessage) 
{
    httpMessage.addHeader("Accept", "application/json");
    httpMessage.addHeader("Content-Type", "application/json; charset=UTF-8");
}
于 2013-02-20T16:54:35.260 回答