如果您使用正确的方法,则不必担心在帖子上设置“内容长度”标题。使用 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));
}