使用头部发送HTTP GET请求

16

我想从我的Android应用程序中请求带有GET参数的URL并读取响应。 在请求中,我必须添加一个x-zip头。

URL类似于:

http://example.com/getmethod.aspx?id=111&method=Test

有没有人能够给我提供相应的代码?

有两个重要的事情:它是一个GET请求并且包含x-zip头。

编辑:

try {
    HttpClient client = new DefaultHttpClient();  
    String getURL = "http://example.com/getmethod.aspx?id=111&method=Test";
    HttpGet get = new HttpGet(getURL);
    get.setHeader("Content-Type", "application/x-zip");
    HttpResponse responseGet = client.execute(get);  
    HttpEntity resEntityGet = responseGet.getEntity();  
    if (resEntityGet != null) {  
        //do something with the response
        Log.i("GET ",EntityUtils.toString(resEntityGet));
    }
} catch (Exception e) {
    e.printStackTrace();
}

我使用这段代码,但是遇到了 .net 错误:Object reference not set to an instance of an object...。我认为,但不确定,问题出在 x-zip 头文件上,我的代码头文件是否正确?


Related - Rob Hruska
你可以给我们展示一些你迄今为止尝试过的代码示例吗? - Rob Hruska
你能发一下具体的错误吗?这听起来像是 getmethod.aspx 的问题,而不是 Java 代码的问题。 - Turnsole
3
为什么要在发送 GET 请求时带上 Content-Type 头字段? - Julian Reschke
2个回答

11

以下是我们在应用中使用的一段代码摘录,用于设置请求头。请注意,我们仅在POST或PUT请求时设置CONTENT_TYPE头,但添加标头的一般方法(通过请求拦截器)也用于GET请求。

/**
 * HTTP request types
 */
public static final int POST_TYPE   = 1;
public static final int GET_TYPE    = 2;
public static final int PUT_TYPE    = 3;
public static final int DELETE_TYPE = 4;

/**
 * HTTP request header constants
 */
public static final String CONTENT_TYPE         = "Content-Type";
public static final String ACCEPT_ENCODING      = "Accept-Encoding";
public static final String CONTENT_ENCODING     = "Content-Encoding";
public static final String ENCODING_GZIP        = "gzip";
public static final String MIME_FORM_ENCODED    = "application/x-www-form-urlencoded";
public static final String MIME_TEXT_PLAIN      = "text/plain";

private InputStream performRequest(final String contentType, final String url, final String user, final String pass,
    final Map<String, String> headers, final Map<String, String> params, final int requestType) 
            throws IOException {

    DefaultHttpClient client = HTTPClientFactory.newClient();

    client.getParams().setParameter(HttpProtocolParams.USER_AGENT, mUserAgent);

    // add user and pass to client credentials if present
    if ((user != null) && (pass != null)) {
        client.getCredentialsProvider().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(user, pass));
    }

    // process headers using request interceptor
    final Map<String, String> sendHeaders = new HashMap<String, String>();
    if ((headers != null) && (headers.size() > 0)) {
        sendHeaders.putAll(headers);
    }
    if (requestType == HTTPRequestHelper.POST_TYPE || requestType == HTTPRequestHelper.PUT_TYPE ) {
        sendHeaders.put(HTTPRequestHelper.CONTENT_TYPE, contentType);
    }
    // request gzip encoding for response
    sendHeaders.put(HTTPRequestHelper.ACCEPT_ENCODING, HTTPRequestHelper.ENCODING_GZIP);

    if (sendHeaders.size() > 0) {
        client.addRequestInterceptor(new HttpRequestInterceptor() {

            public void process(final HttpRequest request, final HttpContext context) throws HttpException,
                IOException {
                for (String key : sendHeaders.keySet()) {
                    if (!request.containsHeader(key)) {
                        request.addHeader(key, sendHeaders.get(key));
                    }
                }
            }
        });
    }

    //.... code omitted ....//

}

谢谢您的回答,我错在这里 sendHeaders.put(HTTPRequestHelper.ACCEPT_ENCODING, HTTPRequestHelper.ENCODING_GZIP); - Jovan
addRequestInterceptor是什么......看起来像是拦截自己的请求!?!?! :o - Radu

7

按照你展示的方法,您可以准确地执行以下操作:

get.setHeader("Content-Type", "application/x-zip");

所以你的头部信息没问题,问题可能出在其他与网络服务相关的输入上。你需要在服务器端进行调试。


get.setHeader("Accept-Encoding", "x-zip"); 改为 get.setHeader(Content-Type"", "application/x-zip"); - Jovan
1
@Jovan 啊,这样就有意义多了。当然啦,你可以设置任何标题,它们不一定要有任何意义... :) - vipw

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接