发送请求:
这里使用的是java发送的请求,发送post请求使用了apache的httpclient开源项目。
private static String HTTPHead = "http://localhost/stu.php";
/**
* 发送get请求
*
* @param name
* @param age
*/
public void sendHttpGetRequest(String name, int age) {
URL url = null;
try {
url = new URL(HTTPHead + "name=" + name + "&age=" + age);
URLConnection conn = url.openConnection();
InputStreamReader reader = new InputStreamReader(
conn.getInputStream());
BufferedReader breader = new BufferedReader(reader);
StringBuffer buf = new StringBuffer();
String line = null;
while (null != (line = breader.readLine())) {
buf.append(line);
}
reader.close();
System.out.println(buf.toString());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* 发送post
*
* @param name
* @param age
*/
public void sendHttpPostRequst(String name, int age) {
BufferedReader in = null;
try {
// 定义HttpClient
HttpClient client = new DefaultHttpClient();
// 实例化HTTP方法
HttpPost request = new HttpPost(HTTPHead);
// 创建名/值组列表
List<NameValuePair> parameters = new ArrayList<NameValuePair>();
parameters.add(new BasicNameValuePair("name", name));
parameters.add(new BasicNameValuePair("age", age + ""));
// 创建UrlEncodedFormEntity对象
UrlEncodedFormEntity formEntiry = new UrlEncodedFormEntity(
parameters);
request.setEntity(formEntiry);
// 执行请求
HttpResponse response = client.execute(request);
// 获取输入流
in = new BufferedReader(new InputStreamReader(response.getEntity()
.getContent()));
StringBuffer sb = new StringBuffer("");
String line = "";
while ((line = in.readLine()) != null) {
sb.append(line);
}
in.close();
String result = sb.toString();
System.out.println(result);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (in != null) {
try {
in.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
接受请求:
php接受到http请求,然后解析获取请求参数,并返回给客户端。
<?php
//连接服务器
$conn=mysql_connect('localhost','root','');
//状态
if(!$conn){
echo "connection failed";
exit;
}
//选择数据库
$sql='use student';
//conn通道进行
$rs=mysql_query($sql,$conn);
//设置字符集
$sql='set names utf8';
mysql_query($sql,$conn);
//获取GET传递的数据:http://localhost/stu.php?name="fujun"&age=20
//$s_name=isset($_GET['name'])?$_GET['name']:'';
//$s_age=isset($_GET['age'])?$_GET['age']:0;
//获取POST传递的数据:http://localhost/stu.php
//"name=putao&age=100"
//file_get_contents:将整个文件读入一个字符串
//php://input:是个可以访问请求的原始数据的只读流。POST 请求的情况下,最好使用 php://input 来代替 $HTTP_RAW_POST_DATA,因为它不依赖于特定的 php.ini 指令
$str = file_get_contents("php://input");
$arr=array();
//parse_str:将字符串解析成多个变量
parse_str($str,$arr);
echo 'name:'.$arr['name']."<br/>".'age:'.$arr['age'];
?>
post的效果:
注意:
1.倒入apache的httpclient项目jar包,不止一个,遇到类没找到的提示的时候,就该看看缺少啥包。
使用这个开源项目的原因是因为这个使用起来很方便,如果使用java.net包也行,就是麻烦一点。