有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java发送带有标头的HTTP GET请求

从我的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();
}

我尝试使用此代码,但得到的代码是。净错误:Object reference not set to an instance of an object... 我想,但我不确定对于x-zip头,我的代码中的头是否正确


共 (2) 个答案

  1. # 1 楼答案

    您完全按照这一行所示进行操作:

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

    因此,您的头很好,问题是web服务的其他一些输入。您需要在服务器端调试它

  2. # 2 楼答案

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