HTTP之java实例
来源:互联网 发布:北汽黄骅分公司 知乎 编辑:程序博客网 时间:2024/06/06 03:07
一、POST与GET的区别:
1、GET是从服务器上获取数据,POST是向服务器传送数据。
2、在客户端, GET方式在通过URL提交数据,数据在URL中可以看到;POST方式,数据放置在HTML HEADER内提交。
3、对于GET方式,服务器端用Request.QueryString获取变量的值,对于POST方式,服务器端用Request.Form获取提交的数。
4、GET方式提交的数据最多只能有1024字节,而POST则没有此限制。
5、安全性问题。正如在(2)中提到,使用 GET 的时候,参数会显示在地址栏上,而 POST 不会。所以,如果这些数据是中文数据而且是非敏感数据,那么使用 GET ;如果用户输入的数据不是中文字符而且包含敏感数据,那么还是使用 POST为好。
二、Java中的Http编程主要有两种
1、标准的Java接口
2、标准的Apache接口
三、标准的Java接口编程
1、GET方式
- import java.io.ByteArrayOutputStream;
- import java.io.IOException;
- import java.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")));
- }
- }
总结:
对于普通的Http编程可以选择GET方式或者POST方式,但对于更高要求的HTTP编程,Apache提供 的标准接口则更为灵活。附Apache编程的JAR包和XMLPull解析时用到的JAR包:Apache编程时用到的JAR包:点击打开链接XMLPull解析时用到的JAR包:点击打开链接
阅读全文
0 0
- HTTP之java实例
- java网络编程之Http多线程下载应用实例
- java网络编程之Http多线程下载应用实例
- HTTP协议 之 实例分析
- java发送http请求实例
- APP接口自动化测试JAVA+TestNG之HTTP接口测试实例
- Java之Http请求
- java之http协议
- Loadrunner之HTTP接口测试脚本实例
- Java之Dom实例
- java实例之字符串
- Thrift之java实例
- java代理请求http(实例)
- Java 发起http GET POST请求实例
- java后台HttpClient调用http接口实例
- java 之 模拟http请求
- JAVA之HTTP,Servlet项目
- java实例之打印日期
- systemProperty的使用
- Retrofit打印请求地址和返回内容
- WPF(MVVM)主窗口关闭时 弹窗提示是否关闭
- SSH 整合实例
- poj1958 Strange Towers of Hanoi(递归)
- HTTP之java实例
- 韦东山第12课-字符设备驱动、按键查询、copy_to_user
- PHP的数据库操作
- 11. Container With Most Water
- 无法再Web服务器上启动调试。基础连接已经关闭:发送时发生错误。
- ITelephony接口和ISms接口以及AIDL
- Codeforces Round #433 Jury Meeting
- ceph rbd 块命令 块扩容 创建快照 rbd分层 rbd快照克隆 可写快照 rbd 导入导出,池、块、快照命令
- 2017年9月7日10:47:23