JAVA模拟HTTP发送请求
maven项目引入依赖,费maven项目手动引入jar包
- <dependency>
-
<groupId>commons-httpclient</groupId>
-
<artifactId>commons-httpclient</artifactId>
-
<version>3.1</version>
-
- </dependency>
引入依赖
-
import org.apache.commons.httpclient.methods.GetMethod;
-
import java.net.*;
-
import org.apache.commons.httpclient.HttpClient;
-
import org.apache.commons.httpclient.methods.PostMethod;
模拟get请求
-
HttpClient client = new HttpClient();
-
String name = "张三";
-
//get请求
-
GetMethod getMethod = new GetMethod("http://15.16.23.37:8999/api/getMessage?name="+name);
-
//post请求
-
//PostMethod postMethod= new PostMethod("http://15.16.23.37:8999/api/getMessage?name="+name);
-
client.executeMethod(getMethod);
-
byte[] responseModel = getMethod.getResponseBody();
-
String resultModel = new String(responseModel,"UTF8");
-
JSONObject json = new JSONObject(resultModel);
-
System.out.println(json);