网络请求 HttpClient 使用

1.导入包

import java.net.URI;

import org.apache.http.HttpEntity;

import org.apache.http.HttpResponse;

import org.apache.http.client.HttpClient;

import org.apache.http.client.methods.HttpPost;

import org.apache.http.client.utils.URIBuilder;

import org.apache.http.entity.StringEntity;

import org.apache.http.impl.client.HttpClients;

import org.apache.http.util.EntityUtils;


2.创建 httpclient 实例,并组装请求内容

public static void main(String[] args) {

HttpClient httpClient = HttpClients.createDefault();

try {

// 创建请求链接地址

URIBuilder uriBuilder = new URIBuilder("https://www.baidu.com");

// set 后加参数, ?language=**

uriBuilder.setParameter("language", "语言");

// 通过 builder 生成请求 uri

URI uri = uriBuilder.build();

// 创建 post 请求,或者 GET  PUT

HttpPost request = new HttpPost(uri);

// 设置请求头

// 请求数据格式设置

request.setHeader("Content-Type", "multipart/form-data");

// 请求 OCP-APIM-订阅密钥 设置

request.setHeader("Ocp-Apim-Subscription-Key", "密钥");

// 请求体

StringEntity reqEntity = new StringEntity("请求体内容");

request.setEntity(reqEntity);

// 使用 httpclient 执行请求, 多态,返回请求结果

HttpResponse response = httpClient.execute(request);

// 请求状态

int code = response.getStatusLine().getStatusCode();

// 返回响应结果内容

HttpEntity entity = response.getEntity();

if (entity != null) {

// 请求内容字符串形式

String result = EntityUtils.toString(entity);

System.out.println(result);

}

} catch (Exception e) {

// TODO: handle exception

}

}

你可能感兴趣的:(网络请求 HttpClient 使用)