码迷,mamicode.com
首页 > 编程语言 > 详细

URL encode 与 URL decode 的C语言实现

时间:2014-12-09 12:25:25      阅读:252      评论:0      收藏:0      [点我收藏+]

标签:des   style   blog   http   io   ar   color   os   使用   

   项目中遇到和java通信的问题,在读取sessionkey后再次发给对方的时候,总是出现session错误的提示。然后就查阅了下面的资料:java.net.URLEncode编码 与 URLDecode解码问题

网页中的表单使用POST方法提交时,数据内容的类型是 application/x-www-form-urlencoded,这种类型会:
1.字符"a"-"z","A"-"Z","0"-"9",".","-","*",和"_" 都不会被编码;
  3.将非文本内容转换成"%xy"的形式,xy是两位16进制的数值;
  4.在每个 name=value 对之间放置 & 符号。
  2.将空格转换为加号 (+) ;


看下面的例子:打开一个网页抓取他的sessionKey然后 查看其它连接请求使用的sessionkey的值进行比较:
  登录网站时回复的:  "sessionkey" : "8IKBGDRaqQzBASQ5Mrq+Uxp6sbA="
利用session访问网站其它内容时发送的 :sessionkey=8IKBGDRaqQzBASQ5Mrq%2BUxp6sbA%3D

#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <sys/types.h>

#include "url.h"

static unsigned char hexchars[] = "0123456789ABCDEF";

static int php_htoi(char *s)
{
	int value;
	int c;

	c = ((unsigned char *)s)[0];
	if (isupper(c))
		c = tolower(c);
	value = (c >= ‘0‘ && c <= ‘9‘ ? c - ‘0‘ : c - ‘a‘ + 10) * 16;

	c = ((unsigned char *)s)[1];
	if (isupper(c))
		c = tolower(c);
	value += c >= ‘0‘ && c <= ‘9‘ ? c - ‘0‘ : c - ‘a‘ + 10;

	return (value);
}


char *php_url_encode(char const *s, int len, int *new_length)
{
	register unsigned char c;
	unsigned char *to, *start;
	unsigned char const *from, *end;
	
	from = (unsigned char *)s;
	end  = (unsigned char *)s + len;
	start = to = (unsigned char *) calloc(1, 3*len+1);

	while (from < end) 
	{
		c = *from++;

		if (c == ‘ ‘) 
		{
			*to++ = ‘+‘;
		} 
		else if ((c < ‘0‘ && c != ‘-‘ && c != ‘.‘) ||
				 (c < ‘A‘ && c > ‘9‘) ||
				 (c > ‘Z‘ && c < ‘a‘ && c != ‘_‘) ||
				 (c > ‘z‘)) 
		{
			to[0] = ‘%‘;
			to[1] = hexchars[c >> 4];
			to[2] = hexchars[c & 15];
			to += 3;
		}
		else 
		{
			*to++ = c;
		}
	}
	*to = 0;
	if (new_length) 
	{
		*new_length = to - start;
	}
	return (char *) start;
}


int php_url_decode(char *str, int len)
{
	char *dest = str;
	char *data = str;

	while (len--) 
	{
		if (*data == ‘+‘) 
		{
			*dest = ‘ ‘;
		}
		else if (*data == ‘%‘ && len >= 2 && isxdigit((int) *(data + 1)) && isxdigit((int) *(data + 2))) 
		{
			*dest = (char) php_htoi(data + 1);
			data += 2;
			len -= 2;
		} 
		else 
		{
			*dest = *data;
		}
		data++;
		dest++;
	}
	*dest = ‘/0‘;
	return dest - str;
}


参考资料:http://blog.csdn.net/langeldep/article/details/6264058

URL encode 与 URL decode 的C语言实现

标签:des   style   blog   http   io   ar   color   os   使用   

原文地址:http://blog.csdn.net/sjin_1314/article/details/41820499

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!