JAVA发送HTTP请求的方式有哪些
短信预约 -IT技能 免费直播动态提醒
这篇文章主要介绍“JAVA发送HTTP请求的方式有哪些”的相关知识,小编通过实际案例向大家展示操作过程,操作方法简单快捷,实用性强,希望这篇“JAVA发送HTTP请求的方式有哪些”文章能帮助大家解决问题。
1. HttpURLConnection
使用JDK原生提供的net,无需其他jar包,代码如下:
import com.alibaba.fastjson.JSON;import java.io.BufferedReader;import java.io.InputStream;import java.io.InputStreamReader;import java.io.OutputStream;import java.net.HttpURLConnection;import java.net.URL;import java.util.HashMap;import java.util.Map; public class HttpTest1 { public static void main(String[] args) { HttpURLConnection con = null; BufferedReader buffer = null; StringBuffer resultBuffer = null; try { URL url = new URL("http://10.30.10.151:8012/gateway.do"); //得到连接对象 con = (HttpURLConnection) url.openConnection(); //设置请求类型 con.setRequestMethod("POST"); //设置Content-Type,此处根据实际情况确定 con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); //允许写出 con.setDoOutput(true); //允许读入 con.setDoInput(true); //不使用缓存 con.setUseCaches(false); OutputStream os = con.getOutputStream(); Map paraMap = new HashMap(); paraMap.put("type", "wx"); paraMap.put("mchid", "10101"); //组装入参 os.write(("consumerAppId=test&serviceName=queryMerchantService¶ms=" + JSON.toJSONString(paraMap)).getBytes()); //得到响应码 int responseCode = con.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { //得到响应流 InputStream inputStream = con.getInputStream(); //将响应流转换成字符串 resultBuffer = new StringBuffer(); String line; buffer = new BufferedReader(new InputStreamReader(inputStream, "GBK")); while ((line = buffer.readLine()) != null) { resultBuffer.append(line); } System.out.println("result:" + resultBuffer.toString()); } } catch (Exception e) { e.printStackTrace(); } }}
2. HttpClient
需要用到commons-httpclient-3.1.jar,maven依赖如下:
<dependency> <groupId>commons-httpclient</groupId> <artifactId>commons-httpclient</artifactId> <version>3.1</version></dependency>
代码如下:
import com.alibaba.fastjson.JSON;import org.apache.commons.httpclient.HttpClient;import org.apache.commons.httpclient.methods.PostMethod; import java.io.IOException;import java.util.HashMap;import java.util.Map; public class HttpTest2 { public static void main(String[] args) { HttpClient httpClient = new HttpClient(); PostMethod postMethod = new PostMethod("http://10.30.10.151:8012/gateway.do"); postMethod.addRequestHeader("accept", "* private static String readLine(InputStream is, int contentLe) throws IOException { ArrayList lineByteList = new ArrayList(); byte readByte; int total = 0; if (contentLe != 0) { do { readByte = (byte) is.read(); lineByteList.add(Byte.valueOf(readByte)); total++; } while (total < contentLe);//消息体读还未读完 } else { do { readByte = (byte) is.read(); lineByteList.add(Byte.valueOf(readByte)); } while (readByte != 10); } byte[] tmpByteArr = new byte[lineByteList.size()]; for (int i = 0; i < lineByteList.size(); i++) { tmpByteArr[i] = ((Byte) lineByteList.get(i)).byteValue(); } lineByteList.clear(); return new String(tmpByteArr, encoding); }}
6. RestTemplate
RestTemplate 是由Spring提供的一个HTTP请求工具。比传统的Apache和HttpCLient便捷许多,能够大大提高客户端的编写效率。代码如下:
import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.http.client.ClientHttpRequestFactory;import org.springframework.http.client.SimpleClientHttpRequestFactory;import org.springframework.web.client.RestTemplate; @Configurationpublic class RestTemplateConfig { @Bean public RestTemplate restTemplate(ClientHttpRequestFactory factory){ return new RestTemplate(factory); } @Bean public ClientHttpRequestFactory simpleClientHttpRequestFactory(){ SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory(); factory.setConnectTimeout(15000); factory.setReadTimeout(5000); return factory; }} @AutowiredRestTemplate restTemplate; @Testpublic void postTest() throws Exception { MultiValueMap<String, String> requestEntity = new LinkedMultiValueMap<>(); Map paraMap = new HashMap(); paraMap.put("type", "wx"); paraMap.put("mchid", "10101"); requestEntity.add("consumerAppId", "test"); requestEntity.add("serviceName", "queryMerchant"); requestEntity.add("params", JSON.toJSONString(paraMap)); RestTemplate restTemplate = new RestTemplate(); System.out.println(restTemplate.postForObject("http://10.30.10.151:8012/gateway.do", requestEntity, String.class));}
关于“JAVA发送HTTP请求的方式有哪些”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识,可以关注编程网行业资讯频道,小编每天都会为大家更新不同的知识点。
免责声明:
① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。
② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341