Java HttpUtil

Java HttpUtil

添加一下依赖

	<dependency>
		<groupId>org.apache.httpcomponents</groupId>
		<artifactId>httpclient</artifactId>
		<version>4.5.4</version>
	</dependency>
	<dependency>
		<groupId>org.apache.httpcomponents</groupId>
		<artifactId>httpcore</artifactId>
		<version>4.4.8</version>
	</dependency>

大概步骤_Get

  1. 创建CloseableHttpClient
  2. 创建HttpGet对象,传入url
  3. httpclient执行请求,用HttpResponse接受返回数据
  4. 使用HttpEntity在response中获取entity
  5. 将entity转化成string,再规范成JsonObject

大概步骤_Post

  1. 创建CloseableHttpClient
  2. 创建HttpPost对象,传入url
  3. 为httppost对象设置传递参数
  4. httpclient执行请求,用HttpResponse接受返回数据
  5. 使用HttpEntity在response中获取entity
  6. 将entity转化成string,再规范成JsonObject

具体代码如下:

package com.exercise.demo;

import java.io.IOException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;

import net.sf.json.JSONObject;


public class HttpUtil {

	public static JSONObject doGet(String url) {
		CloseableHttpClient httpclient = HttpClientBuilder.create().build();
		HttpGet httpget = new HttpGet(url);
		JSONObject jsonObj = null;
		try {
			HttpResponse response = httpclient.execute(httpget);
			HttpEntity entity = response.getEntity();
			if(entity!=null) {
				String result = EntityUtils.toString(entity,"UTF-8");
				jsonObj = JSONObject.fromObject(result);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		return jsonObj;
	}
	
	public static JSONObject doPost(String url,String json) {
		CloseableHttpClient httpclient = HttpClientBuilder.create().build();
		HttpPost httpPost = new HttpPost(url);
		JSONObject jsonObj = null;
		try {
			httpPost.setEntity(new StringEntity(json,"UTF-8"));
			HttpResponse response = httpclient.execute(httpPost);
			HttpEntity entity = response.getEntity();
			if(entity!=null) {
				String result = EntityUtils.toString(entity, "UTF-8");
				jsonObj = JSONObject.fromObject(result);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return jsonObj;
	}
}

*Ending~~~~~~感谢阅读*

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值