Java发送http的get、post、put请求
1. HTTP GET请求
/*** 向指定URL发送GET方法的请求* @param url 发送请求的URL * @param param 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。* @return URL 所代表远程资源的响应结果
*/public static String httpGet(String reqUrl, Map<String, String> headers){return httpRequest(reqUrl, headers);}public static String httpRequest(String reqUrl, Map<String, String> otherHeaders){URL url;try {url = new URL(reqUrl);// 打开和URL之间的连接HttpURLConnection connection = (HttpURLConnection) url.openConnection();//设置用户名密码String userName = "admin";String password = "nsfocus";String auth = userName + ":" + password;BASE64Encoder enc = new BASE64Encoder();String encoding = enc.encode(auth.getBytes()); conn.setDoOutput(true);
// conn.setDoInput(true);
// conn.setUseCaches(false);
// //默认为GET请求
// conn.setRequestMethod("GET");conn.setRequestProperty("Authorization", "Basic " + encoding);// 设置通用的请求属性for(Entry<String, String> entry : otherHeaders.entrySet()){connection.setRequestProperty(entry.getKey(), entry.getValue()); }// 建立实际的连接connection.connect();// 定义 BufferedReader输入流来读取URL的响应BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(),"utf-8"));StringBuilder sb = new StringBuilder();String line="";while ((line = reader.readLine()) != null){sb.append(line);}reader.close();connection.disconnect();return sb.toString();//对返回数据进行解析处理String result = sb.toString();root = mapper.readTree(result);Iterator<JsonNode> rootNode = root.elements();while(rootNode.hasNext()){JsonNode c = rootNode.next();JsonNode sites = c.path("site");String ids = sites.path("id").toString();//substring方法,"qiqishuang"去除引号id = ids.substring(1, ids.length()-1);}} catch (IOException e) {log.error("error while getting request: {}", e.getMessage());return id;} }
2. HTTP POST请求
/*** 向指定URL发送POST方法的请求* @param url 发送请求的URL* @return URL 所代表远程资源的响应结果
*/public static String httpPost(String reqUrl, String content, Map<String, String> headers){return httpRequest(reqUrl, "POST", content, headers);}public static String httpRequest(String reqUrl, String method, String content, Map<String, String> headers){URL url;try {// 打开和URL之间的连接url = new URL(reqUrl);HttpURLConnection connection = (HttpURLConnection) url.openConnection();connection.setDoOutput(true);// Read from the connection. Default is true.connection.setDoInput(true);// Set the post method. Default is GETconnection.setRequestMethod(method);// Post cannot use cachesconnection.setUseCaches(false);connection.setInstanceFollowRedirects(true);for(Entry<String, String> entry : headers.entrySet()){connection.setRequestProperty(entry.getKey(), entry.getValue()); }connection.connect();DataOutputStream out = new DataOutputStream(connection.getOutputStream());// The URL-encoded contendout.writeBytes(content); out.flush();out.close(); // flush and close// 定义 BufferedReader输入流来读取URL的响应BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(),"utf-8"));StringBuilder sb = new StringBuilder();String line="";while ((line = reader.readLine()) != null){sb.append(line);}reader.close();connection.disconnect();return sb.toString();} catch (IOException e) {log.error("error while posting request: {}", e.getMessage());return null;} }
3. HTTP PUT请求
public void httpPut(String dst_ip) {GlobalConfig global = GlobalConfig.getInstance();String urlStr = global.sncHost + "/devices/1/acl/aclGroups/aclGroup";//create xml info pushed to controllerString xmlInfo = createXmlInfo(dst_ip);//establish connection and push policy to snc controllertry {URL url = new URL(urlStr);HttpURLConnection conn = (HttpURLConnection)url.openConnection();conn.setRequestMethod("PUT");conn.setDoInput(true);conn.setDoOutput(true);OutputStream os = conn.getOutputStream(); os.write(xmlInfo.getBytes("utf-8")); os.flush();os.close(); BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));String line = "";String result = "";while( (line =br.readLine()) != null ){result += line;}log.info(result);br.close();} catch (Exception e) {log.info("Error in pushing policy now");e.printStackTrace(); }}
Java发送http的get、post、put请求相关推荐
- java发送http的get、post请求
Http请求类 package wzh.Http;import java.io.BufferedReader; import java.io.IOException; import java.io.I ...
- http get post java_java发送http的get、post请求实现代码
Http请求类 package wzh.Http; import java.io.BufferedReader; import java.io.IOException; import java.io. ...
- html post 图片,如何发送图片作为多部分POST请求的一部分 - Java HtmlUnit
我正尝试使用Java将验证码提交给decaptcher.com. Decaptcher并没有很好的解释如何使用他们的API,所以我想弄清楚如何使用HTTP POST请求来提交验证码.下面是示例代码,我 ...
- Java发送form-data请求实现文件上传
如何使用Java发送form-data格式的请求上传multipart文件? 封装了以下工具类: package com.leeyaonan.clinkz.common.util;import jav ...
- java post 注册_利用JAVA发送POST请求(垃圾注册就是这么产生的) | 学步园
大伙都知道利用JAVA的net包的URL类和 URLConnection可以得到网页源代码(这个应该是蜘蛛程序的锥形吧),但是向网页发送数据怎么办呢,GET请求很好处理,直接在网址后面加参数就可以了, ...
- java发送post请求上传文件和json数据
java发送post请求上传文件和json数据 因为第三方的上传服务post参数使用了两个@requestpart参数. 但是feign不可以使用两个@requestpart参数.会报错:java.l ...
- JAVA发送HTTP同步请求和异步请求
JAVA发送HTTP同步请求和异步请求 同步请求:每一次执行httpClient.execute方法时都是阻塞的,必须等待到响应才能继续往下走. CloseableHttpClient httpCli ...
- java发送get请求,并带上参数,HTTP和HTTPS都可以
//java发送get请求,并带上参数public static String send_Get(String encode_data){CloseableHttpClient httpClient ...
- java发送get请求_java发送http get请求的两种方法(总结)
长话短说,废话不说 一.第一种方式,通过HttpClient方式,代码如下: public static String httpGet(String url, String charset) thro ...
- httpf发送 json_Java用HttpClient3发送http/https协议get/post请求,发送map,json,xml,txt数据...
使用的是httpclient 3.1, 使用"httpclient"4的写法相对简单点,百度:httpclient https post 当不需要使用任何证书访问https网页时, ...
最新文章
- 双向链表(C++实现)
- 傻瓜式Linux之一:系统安装
- eclipse format的时候如何让@param后不换行
- python文件和目录操作方法大全(含实例)
- 报错:selenium.common.exceptions.SessionNotCreatedException: Message: session not created: This versio
- Java读取Excel文件转换成JSON并转成List——(七)
- cocos2d-x中使用Http
- 常用正则表达式(regular expression)
- Gravatar是什么?全球通用头像简单介绍与使用教程
- 批量生成横断面_批量生动生成填充图案的边界线
- 神经网络 demo(斯坦福)
- java服务写在哪里_【Java学习笔记】如何写一个简单的Web Service
- 当数据库新增字段后,接下来需要做的操作(备忘录)
- 升级sp1后文档无法编辑
- 孤立森林(Isolation Forest)
- 4个步骤:聚类分析如何分析用户?
- Redis巡检及优化建议
- 2019-01-25T01:30:00.000+0000 格式转换
- 阿里云ECS共享型n4服务器1核2G怎么样?
- android pick file,Materia风格的Android文件选择器:MaterialFilePicker_Android_移动开发