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

Http协议编程的三种方式

2015-12-27 13:54 423 查看
POST与GET的区别:1、GET是从服务器上获取数据,POST是向服务器传送数据。2、在客户端, GET方式在通过URL提交数据,数据在URL中可以看到;POST方式,数据放置在HTML HEADER内提交。3、对于GET方式,服务器端用Request.QueryString获取变量的值,对于POST方式,服务器端用Request.Form获取提交的数据。4、GET方式提交的数据最多只能有1024字节,而POST则没有此限制。

Java中的Http编程主要有两种,一种是标准的Java接口,另一种是标准的Apache接口,下面分别说明这两种方法是如何实现的。

一、标准的Java接口编程

1、Get方法

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java
4000
.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

public class http_get1 {
// public static final String path =
// "http://192.168.137.103:8080/MyHttp/servlet/LoginAction";
public static final String path = "http://localhost:8080/MyHttp/servlet/LoginAction";
public static String getStringFromStream(InputStream is) {
String str = "";
ByteArrayOutputStream bos = new ByteArrayOutputStream();
int len = 0;
byte[] data = new byte[1024];
if(is!=null){
try {
while ((len = is.read(data)) != -1) {
bos.write(data, 0, len);
}
str = new String(bos.toByteArray(), "utf-8");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return str;
}
public static InputStream useGetMethod(Map<string, string=""> map,
String encode) {
InputStream is = null;
StringBuffer sb = new StringBuffer(path);
sb.append("?");
if (map != null && !map.isEmpty()) {
for (Map.Entry<string, string=""> entry : map.entrySet()) {     sb.append(entry.getKey()).append("=").append(entry.getValue())
.append("&");
}
sb.deleteCharAt(sb.length() - 1);
System.out.println(sb.toString());
URL url = null;
OutputStream os = null;
try {
url = new URL(sb.toString());
if (url != null) {
HttpURLConnection con = (HttpURLConnection) url
.openConnection();
con.setRequestMethod("GET");
con.setConnectTimeout(3000);
con.setDoInput(true);
con.setDoOutput(true);
os = con.getOutputStream();
os.write(sb.toString().getBytes(encode));
os.close();
if (con.getResponseCode() == 200) {
is = con.getInputStream();
}
}
} catch (Exception e) {
}
}
return is;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Map<string, string=""> map = new HashMap<string, string="">();
map.put("username", "admin");
map.put("password", "1243");
String str = getStringFromStream(useGetMethod(map, "utf-8"));
System.out.println(str);
}
}


2、Post方法

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

public class http_post1 {
// 使用POST请求与GET请求的区别就是POST请求不需要封装请求路径,只需要封装请求参数
public static InputStream usePostMethod(Map<string, string=""> map,
String encode) {
StringBuffer buffer = new StringBuffer();
InputStream is = null;
OutputStream os = null;
if (map != null && !map.isEmpty()) {
for (Map.Entry<string, string=""> entry : map.entrySet()) {
try {
buffer.append(entry.getKey()).append("=")
.append(entry.getValue())
// .append(URLEncoder.encode(entry.getValue(),
// encode))
.append("&");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
buffer.deleteCharAt(buffer.length() - 1);
System.out.println(buffer.toString());
}
try {
URL url = new URL(http_get1.path);
if (url != null) {
HttpURLConnection con = (HttpURLConnection) url
.openConnection();
con.setDoInput(true);
con.setDoOutput(true);
con.setRequestMethod("POST");
con.setConnectTimeout(3000);
byte[] tdata = buffer.toString().getBytes();
// con.setRequestProperty("Content-Type",
// "application/x-www-form-urlencoded");
// con.setRequestProperty("Content-Length",
// String.valueOf(tdata.length));
os = con.getOutputStream();
os.write(tdata);
os.close();
if (con.getResponseCode() == 200) {
is = con.getInputStream();
}
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return is;
}
public static void main(String[] args) {
Map<string, string=""> map = new HashMap<string, string="">();
map.put("username", "admin");
map.put("password", "123");        System.out.println(http_get1.getStringFromStream(usePostMethod(map,
"utf-8")));
}
}


二、Apache接口

import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

public class http_myapache {
public static InputStream useApacheMethod(Map<string, string=""> map,
String encode) {
InputStream is = null;
List<namevaluepair> list = new ArrayList<namevaluepair>();
for (Map.Entry<string, string=""> entry : map.entrySet()) {
list.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
try {
// 封装请求参数
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, encode);
// 设置请求参数
HttpPost post = new HttpPost(http_get1.path);
post.setEntity(entity);
// 执行请求
DefaultHttpClient client = new DefaultHttpClient();
HttpResponse response = client.execute(post);
// 获取状态码
if (response.getStatusLine().getStatusCode() == 200) {
is = response.getEntity().getContent();
}
} catch (Exception e) {
// TODO: handle exception
}
return is;
}
public static void main(String[] args) {
Map<string, string=""> map = new HashMap<string, string="">();
map.put("username", "admin");
map.put("password", "123");     System.out.println(http_get1.getStringFromStream(useApacheMethod(map,
"utf-8")));
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息