java怎么使用fastjson接收带有GBK字符集的http请求完整代码
时间: 2024-06-10 22:06:23 浏览: 187
以下是Java使用fastjson接收带有GBK字符集的http请求的示例代码,其中包括了中文注释:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.Feature;
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.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
public class FastJsonDemo {
public static void main(String[] args) throws IOException {
// 构建HttpClient对象
HttpClient httpClient = HttpClients.createDefault();
// 通过HttpPost创建请求对象
HttpPost httpPost = new HttpPost("http://example.com/api");
// 设置请求参数
JSONObject jsonObject = new JSONObject();
jsonObject.put("param1", "value1");
jsonObject.put("param2", "value2");
StringEntity stringEntity = new StringEntity(jsonObject.toString(), ContentType.APPLICATION_JSON);
httpPost.setEntity(stringEntity);
// 发送请求并获取响应
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
// 获取响应结果,并指定编码为GBK
String result = EntityUtils.toString(httpEntity, Charset.forName("GBK"));
// 解析响应结果,使用fastjson库进行解析
JSONObject responseJson = JSON.parseObject(result, Feature.InitStringFieldAsEmpty);
// 输出解析结果
System.out.println("解析结果:");
System.out.println(responseJson.toJSONString());
}
}
阅读全文