3

我在 Android 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 对象来调用它,Google 建议从现在开始使用它,但这也遇到了同样的问题。

我已经能够毫无问题地从 iOS 和 .NET 发出这个请求调用,所以我知道这不是服务。

更新#1

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

更新#2

我终于能够解决问题。该问题是由 Base64 encodeToString 方法向值添加不可见字符引起的。它迫使标题损坏。我使用的是默认设置 0 或 Base64.DEFAULT。我将值更改为 Base64.NO_WRAP,它解决了这个问题。

4

1 回答 1

0

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

查看此来源(搜索长度)以查看 API 如何在帖子中为您处理长度的示例。

您应该评估将用于 http 的库并找到显示诸如“setEntity”之类的方法的 POST 示例来设置帖子的正文。这样,您将不会收到与内容长度相关的错误。看例子

示例代码“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));
}
于 2013-04-26T04:39:39.223 回答