1、首先要注意引入的包
<dependency>
<groupId>commons-httpclient</groupId>
<artifactId>commons-httpclient</artifactId>
<version>3.1</version>
</dependency>
<dependency>
<groupId>net.sf.json-lib</groupId>
<artifactId>json-lib</artifactId>
<version>2.4</version>
<classifier>jdk15</classifier>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId>
<version>4.4.5</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.1.2</version>
</dependency>
</dependencies>
2、使用get方法请求
HttpClient client =
new HttpClient();
//创建get请求
GetMethod get =
new GetMethod(
"
http://127.0.0.1:8959/task/pushOrder
" +
"?top=1");
//发送get请求
int code = client.executeMethod(get);
//处理返回结果
System.
out.println(
"code = " + code +
",message=" + get.getResponseBodyAsString());
//释放连接
get.releaseConnection();
3、使用post + json方法请求
package com.example.demo.httpclient;
import net.sf.json.JSONObject;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
public class MyHttpClient {
public static void main(String[] args) throws Exception{
DefaultHttpClient client = new DefaultHttpClient();
HttpClient httpClient = null;//无法初始化
HttpPost httpPost = new HttpPost("http://localhost:8060/payment/product/is_support.html");
JSONObject object = new JSONObject();
object.put("product_type", "3216");
object.put("channel_type", "9125");
object.put("business_type", "1005");
object.put("language", "7801");
StringEntity entity = new StringEntity(object.toString(),"utf-8");//解决中文乱码问题
entity.setContentType("application/json");
entity.setContentEncoding("UTF-8");
httpPost.setEntity(entity);
HttpResponse response = client.execute(httpPost);
System.out.println("code=" + response.getStatusLine().getStatusCode());
}
}