程序员日常工作中,发送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;
@Configuration
public 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;
}
}
@Autowired
RestTemplate restTemplate;
@Test
public 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请求的多种方式的文章就介绍到这了,更多相关JAVA发送HTTP请求方式内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!