java学习-get和post请求
String url = url + "?" + params
URL connURL = new URL("http://www.xxxx./")
HttpURLConnection httpConn = (HttpURLConnection) connURL.openConnection();
3、设置通用的属性, —-请求头部信息
httpConn.setRequestProperty("Accept", "*/*");
串行连接:1、打开连接 2、请求 3、处理 4、响应 5、关闭连接 重复上面步骤 持久连接:1、打开连接 2、请求 3、处理 4、响应 第二次直接到2操作, 发送请求 持久连接第一次请求后不会关闭连接,下次再发送请求时就不需要再建立连接了
参考资料
Http持久连接与HttpClient连接池
httpConn.connect();
httpConn.getHeaderField("keyName");
// 响应头部获取 Map<String, List<String>> headers = httpConn.getHeaderFields(); // 遍历所有的响应头字段 for (String key : headers.keySet()) { System.out.println(key+": "+httpConn.getHeaderField(key)); }
这是模拟访问www.baidu.com返回的response头部信息
// 定义BufferedReader输入流来读取URL的响应,并设置编码方式 BufferedReader in= null; in = new BufferedReader(new InputStreamReader(httpConn .getInputStream(), "UTF-8"));//通用编码格式为utf-8 String line; // 读取返回的内容 while ((line = in.readLine()) != null) { result += line; } httpConn.disconnect();//主动断开httpConn连接
finally{ try { if (in != null) { in.close(); } } catch (IOException ex) { ex.printStackTrace(); } }
上面是一个get请求的正常流程,当然其中的读取内容的方式有很多种,有些可以直接保存在电脑的文件中,这些方式先不考虑
一个get请求需要注意的几点:
- 请求参数,中文,其它的转义符号需要进行编码
String url = "http://www.baidu.com"; String ss="你是逗逼吗"; try { System.out.println(java.net.URLEncoder.encode(url,"UTF-8")); System.out.println(java.net.URLEncoder.encode(ss,"UTF-8")); } catch (UnsupportedEncodingException e) { e.printStackTrace(); }
输出结果:
- get请求头部最好设置个代理,否则有可能被网站给拦截,拒接访问
,如这里设置为火狐浏览器,模拟浏览器的请求头即可
httpConn.setRequestProperty("User-Agent",
"Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1)");
- 连接断开时候记得一定要把输入输出流给关掉,降低异常出现
如上面的HttpUrlConnection连接,还有bufferReader对象
一个完整的get请求代码
public static String sendGet(String url, LinkedHashMap<String, String> parameters) { String result = "";// 返回的结果 BufferedReader in = null;// 读取响应输入流 StringBuffer sb = new StringBuffer();// 存储参数 String params = "";// 编码之后的参数 try { // 编码请求参数 if (parameters.size() == 1) { for (String name : parameters.keySet()) { sb.append(name).append("=").append( java.net.URLEncoder.encode(parameters.get(name), "UTF-8")); } params = sb.toString(); } else { for (String name : parameters.keySet()) { sb.append(name).append("=").append( java.net.URLEncoder.encode(parameters.get(name), "UTF-8")).append("&"); } String temp_params = sb.toString(); params = temp_params.substring(0, temp_params.length() - 1); } String full_url = url + "?" + params; // 创建URL对象 URL connURL = new URL(full_url); // 打开URL连接 HttpURLConnection httpConn = (HttpURLConnection) connURL .openConnection(); // 设置通用属性 httpConn.setRequestProperty("Accept", "*/*"); httpConn.setRequestProperty("Connection", "Keep-Alive"); httpConn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1)"); // 建立实际的连接 httpConn.connect(); // 响应头部获取 Map<String, List<String>> headers = httpConn.getHeaderFields(); // 遍历所有的响应头字段 for (String key : headers.keySet()) { //System.out.println(key+": "+httpConn.getHeaderField(key)); } // 定义BufferedReader输入流来读取URL的响应,并设置编码方式 in = new BufferedReader(new InputStreamReader(httpConn .getInputStream(), "GBK")); String line; // 读取返回的内容 while ((line = in.readLine()) != null) { result += line; } } catch (Exception e) { e.printStackTrace(); System.out.println("Http请求方法内部问题"); } finally { try { if (in != null) { in.close(); } } catch (IOException ex) { ex.printStackTrace(); } } return result; }
View Code
connection.setRequestProperty("Cookie", "这里放cookie数据");
connection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded;charset=utf-8");
- multipart/form-data类型主要是上传文件时用到;
- application/x-www-form-urlencoded类型主要是提交k-v时用到,当然这种方法也可以将json设置在v中提交json数据;
- application/json类型主要是传递json数据用到,层次比较深的数据;
public static String sendPost(String curl, String param) { String result = "";// 返回的结果 BufferedReader in = null;// 读取响应输入流 try { //创建连接 URL url = new URL(curl); HttpURLConnection connection = (HttpURLConnection) url .openConnection(); connection.setDoOutput(true); 是否打开outputStream 相对于程序,即我们向远程服务器写入数据,默认为false,不打开 connection.setDoInput(true); 输入流,获取到返回的响应内容, 默认为true,所以get请求时可以不设置这个连接信息 connection.setRequestMethod("POST"); //发送请求的方式 connection.setUseCaches(false); //不使用缓存 connection.setInstanceFollowRedirects(true); //重定向,一般浏览器才需要 connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=utf-8"); //设置服务器解析数据的方式 connection.connect(); //POST请求 BufferedWriter out = new BufferedWriter(new OutputStreamWriter(connection.getOutputStream(),"UTF-8")); out.write(param); out.flush(); out.close(); //读取响应 // 定义BufferedReader输入流来读取URL的响应,并设置编码方式 in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8")); String line; // 读取返回的内容 while ((line = in.readLine()) != null) { result += line; } } catch (Exception e) { e.printStackTrace(); System.out.println("Http请求方法内部问题"); } finally { try { if (in != null) { in.close(); } } catch (IOException ex) { ex.printStackTrace(); } } return result; }
post请求不同提交数据方式有对应的解析方法,json解析和文件上传下次再写个专题