使用HttpClient工具调用接口的示例

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());

    }

}

 

 

 

 

 

 

 

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值