发送带有标头的 HTTP GET 请求

2022-09-03 06:45:47

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

网址类似于

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


答案 1

下面是我们在应用中用于设置请求标头的代码摘录。您会注意到,我们仅在 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 ....//

}

答案 2

您可以完全按照以下行显示的方式进行操作:

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

所以你的头文件很好,问题是对Web服务的其他一些输入。您需要在服务器端对其进行调试。


推荐