您的位置:首页 > 理论基础 > 计算机网络

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

2017-10-09 19:18 537 查看
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());

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: