HttpPost Iphone与Android

时间:2011-09-30 17:05:37

标签: android iphone

1)在Iphone上,

- (void) postData:(NSMutableData *)_body withAction:(NSString *)_action binary:(BOOL)_binary
{
    [self stopProcess];



    binary = _binary;

    NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
    NSString *url = [NSString stringWithFormat:API_FORMAT, APP_SERVER, _action, [self getSession]];
    if (debug_switch) {
    NSLog(@"The action is %@", _action);
        NSLog(@"The accessing server API call Datafeed is %@", url);}
    [request setURL:[NSURL URLWithString:url]];
    [request setHTTPMethod:@"POST"];


    //TRACE(@"url: %@", url);

    if(_body != nil)
    {
        NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundary];
        [request addValue:contentType forHTTPHeaderField: @"Content-Type"];
        [request setHTTPBody:_body];
    }

    //con = [NSURLConnection connectionWithRequest:request delegate:self];

    if(con != nil) {
        [con release];
    }
    con = [[NSURLConnection alloc] initWithRequest:request delegate:self];

    if (con) 
    {
        dataDict = nil;
        loading = YES;
        if(receivedData == nil) {
            receivedData = [[NSMutableData data] retain];
        }
        [receivedData setLength:0];
    }

}

static NSString *boundary = @"---------------------------147378274664144922";

@implementation DataFeed

BOOL connectable = NO;

///////////////////////////////

- (NSMutableData *) initContentBody
{
    NSMutableData *body = [NSMutableData data];
    [body appendData:[self addFormData:@"uid" withString:[[UIDevice currentDevice] uniqueIdentifier]]];
    return body;
}


//////////////////////////

- (NSData *) addFormBoundary
{
    return [[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding];
}

//////////////////////////////////////////


- (NSData *) addFormData:(NSString *)_name withInt:(int)_value
{
    return [self addFormData:_name withString:[[NSNumber numberWithInt:_value] stringValue]];
}


- (NSData *) addFormData:(NSString *)_name withFloat:(float)_value
{
    return [self addFormData:_name withString:[[NSNumber numberWithFloat:_value] stringValue]];
}


- (NSData *) addFormData:(NSString *)_name withString:(NSString *)_value
{
    NSMutableData *body = [NSMutableData data];
    [body appendData:[self addFormBoundary]];
    [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\";\r\n\r\n%@", _name, _value] dataUsingEncoding:NSUTF8StringEncoding]];    
    return body;
}

- (NSData *) addFormData:(NSString *)_name filename:(NSString *)_filename withData:(NSData *)_data
{
    NSMutableData *body = [NSMutableData data];
    [body appendData:[self addFormBoundary]];
    [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"; filename=\"%@\"\r\n", _name, _filename] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[[NSString stringWithString:@"Content-Type: application/zip\r\n"] dataUsingEncoding:NSUTF8StringEncoding]]; 
    [body appendData:[[NSString stringWithString:@"Content-Transfer-Encoding: binary\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:_data];    
    return body;
}

2)在Android上,

public void executeHttpPost() throws Exception {
    String address = "";
    HttpClient client = new DefaultHttpClient();
    HttpPost post = new HttpPost(address);

    List<NameValuePair> pairs = new ArrayList<NameValuePair>();
    pairs.add(new BasicNameValuePair("key1", "value1"));
    pairs.add(new BasicNameValuePair("key2", "value2"));
    post.setEntity(new UrlEncodedFormEntity(pairs));

    HttpResponse response = client.execute(post);

}

关于android的正文数据的问题是否可以设置为非json格式,键值对?正如你在iphone上看到的那样,body可以是任何参数,也不一定是键值对。你可以在android上给出一个例子,其中post数据可以是非json格式吗? < / p>

1 个答案:

答案 0 :(得分:2)

您不限于UrlEncodedFormEntity,请查看org.apache.http.HttpEntity界面的“已知间接子类”(位于页面顶部)。

最常用的可能是:

  • ByteArrayEntity:从字节数组中检索其内容的实体。
  • FileEntity:从文件中检索其内容的实体。
  • InputStreamEntity:流式实体从InputStream获取内容。
  • SerializableEntity:获取Serializable个对象并输出其序列化表格
  • StringEntity:从字符串中检索其内容的实体。
  • ,最后是UrlEncodedFormEntity:由url编码对列表组成的实体。

(此列表不完整,请查看以上链接)

以下是如何使用不同类型实体的一些示例:

HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(address);

// a string entity containing JSON:
post.setEntity(new StringEntity("{ \"actually\" : [\"json\", \"this time\"]}");

// or uploading an image file:
post.setEntity(new FileEntity(new File("some/local/image.png"), "image/png");

// or some random bytes:
byte[] randomBytes = new byte[128];
new Random().nextBytes(randomBytes);
post.setEntity(new ByteArrayEntity(randomBytes);

HttpResponse response = client.execute(post);
...

当然,不要一次完成所有操作,只需拨打setEntity()一次!如果您需要MIME多部分请求,请查看this tutorial by Vikas Patel(您需要更新的Apache HTTP客户端JAR)。