您的位置:首页 > 理论基础 > 计算机网络

java Http消息传递之POST和GET两种方法

2015-03-06 22:06 357 查看
/**
* 通过Get方法来向服务器传值和获取信息,
* 这里举例假设的前提是,链接上服务器,服务器直接发送数据给本地
*
* 大体的思路:
* 1、首先通过URL地址来获得链接的借口
* 通过接口,来设置链接超时的时间,请求方式,是否可以输入输出数据
* 得到读取服务器内容的读取流
*
* 2、为存储 从服务器读取到的数据做准备
* 将读取到的数据写入文件或直接得到字符串
* 关闭并刷新读写流
*
*
*/

public static void getMsgByGet(String path){
try {
/*为读取做准备*/

//通过URL路径来创建URL对象
URL url=new URL(path);
//建立连接对象,并设置相应属性
HttpURLConnection conn=(HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5000);
conn.setRequestMethod("GET");
conn.setDoInput(true);
//若连接成功获取输入流,并写入数据
if(conn.getResponseCode()==200){
InputStream in=conn.getInputStream();
/*为写入做准备*/

//设置存放数据的比特数组,
byte[]arr=new byte[1024];
//设置确定接收数组的长度的变量
int len=0;
//创建用来存放从服务器读取来的数据文件
File file=new File("file\\temp.txt");
//创建写入流
FileOutputStream fos=new FileOutputStream(file);

/* 开始读取和写入数据*/
while((len=in.read(arr))!=-1){
fos.write(arr,0,len);
}
fos.flush();
}

} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}


/**
*
* 通过Post方法向服务器发送数据和获取数据;
*
* 主要分
*
* 1、准备要发送到服务器的数据
* 2、为发送数据做准备
* 3、提交数据
* 4、为写入数据做准备
* 5、读取服务器返回的数据并写入
* @throws IOException
*
*
*/

public String getMsg(String path) throws IOException{
//这里发送的数据是一串字符串(你好呀)
StringBuilder sb=new StringBuilder();
sb.append("你好呀");

/*为发送数据做准备*/

//通过URL地址获取URL对象
URL url=new URL(path);
//获取链接对象
HttpURLConnection conn=(HttpURLConnection) url.openConnection();
//设置连接对象的属性
conn.setConnectTimeout(5000);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
//设置提交数据类型(HTML传送数据必须的)
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
//将要传递的数据转换为比特类型
byte[]data=sb.toString().getBytes();
//设置提交数据的长度
conn.setRequestProperty("Content-Length", String.valueOf(data.length));

/*提交数据*/
OutputStream out=conn.getOutputStream();
out.write(data, 0, data.length);
out.close();

//判断发送数据是否成功
if(conn.getResponseCode()==200){
InputStream in=conn.getInputStream();

/*为写入数据做准备*/

ByteArrayOutputStream bos=new ByteArrayOutputStream();

byte []arr=new byte[1024];
int len=0;

/*读取服务器返回的数据并写入*/
while((len=in.read(arr))!=-1){
bos.write(arr, 0, len);
}
byte[]b=bos.toByteArray();
return new String(b,0,b.length,"utf-8");
}

return null;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: