JAVA 发送 POST、GET请求
来源:互联网 发布:ubuntu 17.04 安装qq 编辑:程序博客网 时间:2024/06/06 00:08
GET请求:GET请求会向服务器发索取数据的请求,从而来获取信息,该请求就像数据库的select操作一样,只是用来查询一下数据,不会修改、增加数据,不会影响资源的内容,即该请求不会产生副作用。无论进行多少次操作,结果都是一样的。
post请求:POST是向服务器端发送数据的,但是该请求会改变数据的种类等资源,就像数据库的insert操作一样,会创建新的内容。几乎目前所有的提交操作都是用POST请求的。
javaCode:
-
-
-
-
- public static String get(String url) {
- BufferedReader in = null;
- try {
- URL realUrl = new URL(url);
-
- URLConnection connection = realUrl.openConnection();
-
- connection.setRequestProperty("accept", "*/*");
- connection.setRequestProperty("connection", "Keep-Alive");
- connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
- connection.setConnectTimeout(5000);
- connection.setReadTimeout(5000);
-
- connection.connect();
-
- in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
- StringBuffer sb = new StringBuffer();
- String line;
- while ((line = in.readLine()) != null) {
- sb.append(line);
- }
- return sb.toString();
- } catch (Exception e) {
- LOG.error("Exception occur when send http get request!", e);
- }
-
- finally {
- try {
- if (in != null) {
- in.close();
- }
- } catch (Exception e2) {
- e2.printStackTrace();
- }
- }
- return null;
- }
-
-
-
-
-
-
-
-
-
- public static String jsonPost(String strURL, Map<String, String> params) {
- try {
- URL url = new URL(strURL);
- HttpURLConnection connection = (HttpURLConnection) url.openConnection();
- connection.setDoOutput(true);
- connection.setDoInput(true);
- connection.setUseCaches(false);
- connection.setInstanceFollowRedirects(true);
- connection.setRequestMethod("POST");
- connection.setRequestProperty("Accept", "application/json");
- connection.setRequestProperty("Content-Type", "application/json");
- connection.connect();
- OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream(), "UTF-8");
- out.append(JSONUtil.object2JsonString(params));
- out.flush();
- out.close();
-
- int code = connection.getResponseCode();
- InputStream is = null;
- if (code == 200) {
- is = connection.getInputStream();
- } else {
- is = connection.getErrorStream();
- }
-
-
- int length = (int) connection.getContentLength();
- if (length != -1) {
- byte[] data = new byte[length];
- byte[] temp = new byte[512];
- int readLen = 0;
- int destPos = 0;
- while ((readLen = is.read(temp)) > 0) {
- System.arraycopy(temp, 0, data, destPos, readLen);
- destPos += readLen;
- }
- String result = new String(data, "UTF-8");
- return result;
- }
-
- } catch (IOException e) {
- LOG.error("Exception occur when send http post request!", e);
- }
- return "error";
- }