有 Java 编程相关的问题?

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

java Android DefaultHttpClient POST方法无法设置内容长度,收到Http错误411

我对安卓4.2上的HttpPost有问题。我正在尝试调用托管在服务器中的身份验证服务。NET WebAPI服务

该服务要求请求作为POST方法发出,并提供多个自定义请求头。请求主体向服务发送Json值

以下是我如何撰写我的请求

HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://api.fekke.com/api/account/login");
httppost.addHeader(HTTP.TARGET_HOST, "api.fekke.com");
httppost.addHeader("Accept", "application/json");
httppost.addHeader("Fekke-AccessKey", "some-access-key");
httppost.addHeader("Date", dateString);
httppost.addHeader("Fekke-Signature", "some-encoded-value");
httppost.addHeader("Content-Type", "application/json; charset=utf-8");

String jsonmessage = "{\"Username\": \"myusername\", \"Password\": \"mypassword987\"}";
httppost.setEntity(new StringEntity(jsonmessage, HTTP.UTF_8));

HttpResponse response = httpclient.execute(httppost);

我试着用一个“Content Length”头调用它,它抛出一个异常,表示请求中已经存在该头

我也尝试过使用HttpURLConnection对象来调用它,从现在开始,谷歌建议使用HttpURLConnection对象,但这也遇到了同样的问题

我已经能够从iOS和。NET没有问题,所以我知道这不是服务

更新#1

我通过本地版本的服务运行了下面的示例,当我在其中一个http头中传递哈希值时,我能够将错误隔离到。我使用的是一个JWT安全令牌,它使用HMAC SHA-256哈希算法来设置服务使用的值。这个散列值会导致请求的执行中断

更新#2

我终于解决了这个问题。该问题是由Base64 encodeToString方法向值中添加不可见字符引起的。这迫使头球破发。我使用的是默认设置0或Base64。违约我将值更改为Base64。没有包装,解决了问题


共 (1) 个答案

  1. # 1 楼答案

    如果使用了正确的方法,就不必担心在帖子上设置“内容长度”标题。对于Post,您通常使用一些重载版本的“SetEntity($Type stream/string/encodedArray…)

    看看这个source(搜索长度)来看看API如何处理帖子长度的例子

    您应该评估将用于http的库,并找到显示“setEntity”等方法来设置帖子正文的帖子示例。这样,就不会出现与内容长度相关的错误。见example

    示例代码“HttpConnection”类-使用我评论中的链接

    对于JSON或位图:

    try {                       
        HttpResponse response = null;
        switch (method) {
        case GET:
            HttpGet httpGet = new HttpGet(url);             
            response = httpClient.execute(httpGet);
            break;
        //Note on NIO - using a FileChannel and  mappedByteBuffer may be NO Faster
        // than using std httpcore  http.entity.FileEntity
        case POST:
            //TODO bmp to stream to bytearray for data entity
            HttpPost httpPost = new HttpPost(url); //urlends "audio OR "pic" 
            if (  !url.contains("class") ){                 
                ByteArrayOutputStream stream = new ByteArrayOutputStream();
                //can alter belo for smaller uploads to parse .JPG , 40,strm
                bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);               
                httpPost.setEntity(new ByteArrayEntity(stream.toByteArray()));
    
            }else if(data != null && (url.contains("class"))){
                //bug data is blank
                httpPost.setEntity(new StringEntity(data));
                Log.d(TAG, "DATA in POST run-setup " +data);
            }
    
            response = httpClient.execute(httpPost);
            break;
        case PUT:
            HttpPut httpPut = new HttpPut(url);
            httpPut.setEntity(new StringEntity(data));
            response = httpClient.execute(httpPut);
            break;
        case DELETE:
            response = httpClient.execute(new HttpDelete(url));
            break;
        case BITMAP:
            response = httpClient.execute(new HttpGet(url));
            processBitmapEntity(response.getEntity());
            break;
        }
        if (method < BITMAP)
            processEntity(response.getEntity());
    } catch (Exception e) {
        handler.sendMessage(Message.obtain(handler,
                HttpConnection.DID_ERROR, e));
    }
    

    对于Post中的XML正文:

    try {
        HttpResponse response = null;
        switch (method) {
    
        case POST:
            HttpPost httpPost = new HttpPost(url);
            if (data != null){
                System.out.println(" post data not null ");
                httpPost.setEntity(new StringEntity(data));
            }
            if (entry != null){
                ContentProducer cp = new ContentProducer() {
                    public void writeTo(OutputStream outstream) throws IOException {
    
                         ExtensionProfile ep = new ExtensionProfile();
                         ep.addDeclarations(entry);
                         XmlWriter xmlWriter = new XmlWriter(new OutputStreamWriter(outstream, "UTF-8"));
                         entry.generate(xmlWriter, ep);
                         xmlWriter.flush();
                    }
                };
                httpPost.setEntity(new EntityTemplate(cp));
            }
            httpPost.addHeader("GData-Version", "2");
            httpPost.addHeader("X-HTTP-Method-Override", "PATCH");
            httpPost.addHeader("If-Match", "*");
            httpPost.addHeader("Content-Type", "application/xml");
            response = httpClient.execute(httpPost);
    
            break;
        }
        if (method < BITMAP)
            processEntity(response.getEntity());
    } catch (Exception e) {
        handler.sendMessage(Message.obtain(handler,
                HttpConnection.DID_ERROR, e));
    }