发送POST请求代码---java转oc/c++
来源:互联网 发布:阿里巴巴直接传淘宝 编辑:程序博客网 时间:2024/06/06 08:23
前一段时间做的一个移植项目,做个笔记。
/** * 发送POST请求(以NAME-VALUE格式组织JSON对象) * @param paramName:JSON参数名称 * @param param:JSON参数对象 */public static JSONObject httpPost(String url, String paramName, JSONObject param){//使用NameValuePair来保存要传递的Post参数ArrayList<NameValuePair> paramList = new ArrayList<NameValuePair>();//添加要传递的参数String str = param.toString();paramList.add(new BasicNameValuePair(paramName,/* param.toString()*/str));String s = paramList.toString();//发送POST请求(NAME-VALUE格式),返回JSON对象return httpPost(url,paramList);}/** * 发送POST请求(NAME-VALUE格式) */public static JSONObject httpPost(String url, ArrayList<NameValuePair> paramList){try{//HttpPost对象声明HttpPost httpPost = new HttpPost(url);//设置字符集httpPost.setEntity(new UrlEncodedFormEntity(paramList,HTTP.UTF_8));//取得HttpClient对象HttpClient httpClient = new DefaultHttpClient();//请求HttpCLient,取得HttpResponseString s = httpPost.toString();HttpResponse httpRes = httpClient.execute(httpPost);//请求成功if(httpRes.getStatusLine().getStatusCode() == HttpStatus.SC_OK){//取得返回的字符串String json = EntityUtils.toString(httpRes.getEntity());//计数器清零timeoutCnt = 0;//返回JSON对象return new JSONObject(json);}}catch(Exception e){e.printStackTrace();}//返回[访问服务器异常]JSON对象return clientExceptionJsonObject();}
用扩展后的NSMutableArray*代替java的JSONArray,NSMutableDictionary*代替java的JSONObject。转换成oc代码如下:
扩展后的NSMutableArray,NSMutableDictionary代码:
typedef NSMutableArray* JSONArray;typedef NSMutableDictionary* JSONObject;pthread_mutex_t mutex3=PTHREAD_MUTEX_INITIALIZER;//用于网络连接
/** * HTTP通讯 */@interface NSMutableArray(JSONArray1)-(int)length;-(void)putt:(NSMutableDictionary*)json;-(NSMutableDictionary*)getJSONObject:(int)index;@end@implementation NSMutableArray(JSONArray1)-(int)length{ return [self count];}-(void)putt:(NSMutableDictionary*)json{ [self addObject:json];}-(NSMutableDictionary*)getJSONObject:(int)index{ return (NSMutableDictionary*)[self objectAtIndex:index];}@end@interface NSMutableDictionary(JSONCategories)+(NSMutableDictionary*)dictionaryWithContentsOfJSONURLString:(NSString*)urlAddress;+(NSMutableDictionary*)dictionaryWithContentsOfData:(NSData*)data;-(NSString*)getString:(NSString*)key;-(int)getInt:(NSString*)key;-(double)getDouble:(NSString*)key;-(void)putt:(id)value forKey:(id)key;-(NSMutableArray*)getJSONArray:(NSString*)json;//+(NSDictionary*)httpPost:(NSString*)nUrl name:(NSString*)paramNsName json:(NSDictionary*)jsonParam;+(NSData*)toJSON;@end@implementation NSMutableDictionary(JSONCategories)+(NSMutableDictionary*)dictionaryWithContentsOfJSONURLString:(NSString*)urlAddress{ NSData* data =[NSData dataWithContentsOfURL:[NSURL URLWithString: urlAddress]]; //NSData* data = [NSData dataWithContentsOfURL:[NSURL URLWithString:urlAddress options: error: __autoreleasing NSError* error =nil; id result =[NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error]; if(error !=nil)return nil; return result;}-(NSString*)getString:(NSString*)key{ return (NSString*)[self objectForKey:key];}-(int)getInt:(NSString *)key{ return [((NSString*)[self objectForKey:key]) intValue];}-(double)getDouble:(NSString *)key{ return [((NSString*)[self objectForKey:key]) doubleValue];}-(void)putt:(id)value forKey:(id)key{ return [self setObject:value forKey:key];}-(NSMutableArray*)getJSONArray:(NSString*)json{ return (NSMutableArray*)[self objectForKey:json]; }+(NSMutableDictionary*)dictionaryWithContentsOfData:(NSData*)data{ NSDictionary* dict =[data objectFromJSONData]; NSArray* keys = [dict allKeys]; NSArray* values = [dict allValues]; return [NSDictionary dictionaryWithObjects:values forKeys:keys]; return nil;}
//用oc实现上面java代码,还没添加线程锁//+(NSDictionary*)httpPost:(NSString*)nUrl name:(NSString*)paramNsName json:(NSDictionary*)jsonParam//{ // NSDictionary* dict = [NSDictionary dictionaryWithObject:jsonParam forKey:paramNsName];// NSData* param = [dict toJSON];// // NSURL* url1 = [NSURL URLWithString:nUrl];// NSMutableURLRequest* request= [NSMutableURLRequest requestWithURL:url1]; // [request setHTTPMethod:@"POST"]; // //[request setTimeoutInterval:20.0f];// [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];// [request setHTTPBody:param];// NSURLResponse* response;// NSData* dataReply = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil]; // [jsonParam release];// // if(nil !=response)// {// int statusCode = [(NSHTTPURLResponse*) response statusCode];// NSLog(@"HTTP Status code:%d",statusCode);// if(statusCode==200&&dataReply!=nil)// {// //timeoutCnt = 0;// NSDictionary* ret = [NSMutableDictionary dictionaryWithContentsOfData:dataReply];// [ret retain];// return ret;// }// }// return nil;//}+(NSData*)toJSON{ NSError* error =nil; id result =[NSJSONSerialization dataWithJSONObject:self options:kNilOptions error:&error]; if(error !=nil)return nil; return result;}
//用c++实现java代码,功能与上面注释的代码一样
static JSONObject httpPost(String url, String paramName, JSONObject jsonParam){ pthread_mutex_lock(&mutex3);//添加线程锁 NSString* paramNsName = [NSString stringWithUTF8String:paramName.c_str()]; NSData* data = toJSON(jsonParam); NSString* ss = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]; NSString* ns = [NSString stringWithFormat:@"%@=%@",paramNsName,ss]; [ss release]; NSData* param = [ns dataUsingEncoding:NSUTF8StringEncoding]; NSString* nUrl = [NSString stringWithUTF8String:url.c_str()]; NSURL* url1 = [NSURL URLWithString:nUrl]; NSMutableURLRequest* request= [NSMutableURLRequest requestWithURL:url1]; [request setHTTPMethod:@"POST"]; //[request setTimeoutInterval:20.0f]; [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"]; [request setHTTPBody:param]; NSURLResponse* response; NSData* dataReply = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil]; [jsonParam release];//释放调用者传进来的对象,忌讳,还须改进 if(nil !=response) { int statusCode = [(NSHTTPURLResponse*) response statusCode]; NSLog(@"HTTP Status code:%d",statusCode); if(statusCode==200&&dataReply!=nil) { //NSLog(@"Reply Date length:%d",dataReply.length); timeoutCnt = 0; JSONObject ret = [NSMutableDictionary dictionaryWithContentsOfData:dataReply]; [ret retain]; pthread_mutex_unlock(&mutex3); return ret; } } pthread_mutex_unlock(&mutex3); return clientExceptionJsonObject();}
- 发送POST请求代码---java转oc/c++
- java发送post请求代码
- Java代码发送POST请求
- 使用java代码发送HTTP Post请求
- java代码 发送GET、POST请求
- HTTP JAVA代码发送POST请求
- java代码发送HTTP Post请求
- Java发送Post请求
- java发送post请求
- OC post 请求时发送字符串问题
- 使用Java发送POST、GET请求【转】
- c++libcur发送post请求
- Java代码中利用httpClient发送post、get请求
- 利用JAVA发送POST请求
- Java发送Get/Post请求
- java中发送post请求
- Java发送GET,POST请求
- JAVA发送POST+GET请求
- K-SVD, BM3D等
- 基于C#的字体设计器
- (1) array of string/struct: qsort bsearch
- 【ACM】杭电1036:Average is not Fast Enough!
- 八皇后问题
- 发送POST请求代码---java转oc/c++
- spring3mvc与struts2的区别
- (5) hashtable <key, data> : hcreate hdestroy hsearch
- 内存管理——堆栈等内存的分布
- java的IO流转载
- 关于hdu1872的稳定排序
- JFreeChart的使用
- HDU 4431 Mahjong(枚举,模拟)
- Android的Notification应用详解和PendingIntent的初步剖解