java httpclient 跨域_使用Httpclient 完美解决服务端跨域问题

本文介绍如何使用Java的HttpClient库来处理服务端跨域问题。通过创建HttpClient实例,设置请求头和请求体,发送POST请求到指定URL,从而实现跨域请求并获取响应数据。
摘要由CSDN通过智能技术生成

package com.example.util;

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;

/**

*body 参数参数

* HttpClient工具类

*/

public class HttpUtil {

public static String doPost(String url,String action ,String body) {

String result = null;

HttpClient client = HttpClients.createDefault();

URIBuilder builder = new URIBuilder();

URI uri = null;

try {

uri = builder.setScheme("http")

.setHost(url) // 127.0.0.1:9528/registration_server --- "127.0.0.1:9528"

.setPath(action)//"/registration_server/api/getToken"

.build();

HttpPost post = new HttpPost(uri);

//设置请求头

post.setHeader("Content-Type", "application/json");

// String body = "{\"channelNo\": \"888888\",\"password\": \"123456\"}";

//设置请求体

post.setEntity(new StringEntity(body));

//获取返回信息

HttpResponse response = client.execute(post);

HttpEntity entity=response.getEntity();

// String rtn=EntityUtils.toString(entity);

// JSONObject obj=(JSONObject) JSONObject.parse(rtn);

// System.out.println("data======"+obj.get("data"));

// result =(String) obj.get("data");

return EntityUtils.toString(entity,"utf-8");

} catch (Exception e) {

System.out.println("接口请求失败"+e.getStackTrace());

}

// System.out.println(result);

//return result;

return "";

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值