Java发送HTTP的get,post请求(JSON)

package com.jj.util;
import java.io.IOException;
import java.text.ParseException;

import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
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.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import net.sf.json.JSONObject;

public class HttpUtil {
	/**
	 * 发送post请求
	 * 
	 * @param url
	 *            路径
	 * @param jsonObject
	 *            参数(json类型)
	 * @param encoding
	 *            编码格式
	 * @return
	 * @throws ParseException
	 * @throws IOException
	 */
	public static String doPost(String url, String jsonObject, String  encoding) throws ParseException, IOException {
		String body = "";
		// 创建httpclient对象
		CloseableHttpClient client = HttpClients.createDefault();
		// 创建post方式请求对象
		HttpPost httpPost = new HttpPost(url);
		// 装填参数
		StringEntity s = new StringEntity(jsonObject.toString(), "utf-8");
		s.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
		// 设置参数到请求对象中
		httpPost.setEntity(s);
		System.out.println("请求地址:" + url);
		// System.out.println("请求参数:"+nvps.toString());
		// 设置header信息
		// 指定报文头【Content-type】、【User-Agent】
		// httpPost.setHeader("Content-type",
		// "application/x-www-form-urlencoded");
		
		httpPost.setHeader("Content-type", "application/json");
		httpPost.setHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
		// 执行请求操作,并拿到结果(同步阻塞)
		CloseableHttpResponse response = client.execute(httpPost);
		// 获取结果实体
		HttpEntity entity = response.getEntity();
		if (entity != null) {
			// 按指定编码转换结果实体为String类型
			body = EntityUtils.toString(entity, encoding);
		}
		EntityUtils.consume(entity);
		// 释放链接
		response.close();
		return body;
	}
	
	/**
	 * 发送Get请求
     * json 字符串
     * @param url
     * @param jsonObject
     * @return
     */
    public static String doGet(String url,String param){
	      /* 1 生成 HttpClinet 对象并设置参数 */
	        HttpClient httpClient = new HttpClient();
	        // 设置 Http 连接超时为5秒
	        httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
	      /* 2 生成 GetMethod 对象并设置参数 */
	        GetMethod getMethod = new GetMethod(url);
	        // 设置 get 请求超时为 5 秒
	        getMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 5000);
	        // 设置请求重试处理,用的是默认的重试处理:请求三次
	        getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());
	        String response = "";
	      /* 3 执行 HTTP GET 请求 */
	        try {
	            int statusCode = httpClient.executeMethod(getMethod);
	         /* 4 判断访问的状态码 */
	            if (statusCode != HttpStatus.SC_OK) {
	                System.err.println("请求出错: "+ getMethod.getStatusLine());
	            }
	         /* 5 处理 HTTP 响应内容 */
	            // HTTP响应头部信息,这里简单打印
	            Header[] headers = getMethod.getResponseHeaders();
	            for (Header h : headers)
	                System.out.println(h.getName() + "------------ " + h.getValue());
	            // 读取 HTTP 响应内容,这里简单打印网页内容
	            byte[] responseBody = getMethod.getResponseBody();// 读取为字节数组
	
	            response = new String(responseBody, param);
	            System.out.println("----------response:" + response);
	            // 读取为 InputStream,在网页内容数据量大时候推荐使用
	            // InputStream response = getMethod.getResponseBodyAsStream();
	        } catch (HttpException e) {
	            // 发生致命的异常,可能是协议不对或者返回的内容有问题
	            System.out.println("请检查输入的URL!");
	            e.printStackTrace();
	        } catch (IOException e) {
	            // 发生网络异常
	            System.out.println("发生网络异常!");
	            e.printStackTrace();
	        } finally {
	         /* 6 .释放连接 */
	            getMethod.releaseConnection();
	        }
	        return response;
	    }	
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java发送GET请求传递JSON数据,可以使用HttpClient库来实现。以下是一个示例代码: ```java import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGetWithEntity; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.util.EntityUtils; import java.io.IOException; public class Main { public static void main(String\[\] args) { HttpClient httpClient = HttpClientBuilder.create().build(); String url = "http://example.com/api"; String json = "{\"key\":\"value\"}"; try { HttpGetWithEntity httpGet = new HttpGetWithEntity(url); httpGet.setEntity(new StringEntity(json)); HttpResponse response = httpClient.execute(httpGet); String responseBody = EntityUtils.toString(response.getEntity()); System.out.println(responseBody); } catch (IOException e) { e.printStackTrace(); } } } ``` 在这个示例中,我们使用HttpClient库创建了一个HttpClient对象,并指定了请求的URL和JSON数据。然后,我们创建了一个HttpGetWithEntity对象,并将JSON数据设置为请求的实体。最后,我们执行GET请求并获取响应的内容。 请注意,这只是一个示例代码,你需要根据你的实际情况进行适当的修改。 #### 引用[.reference_title] - *1* [java http get post发送json数据请求](https://blog.csdn.net/somdip/article/details/130584038)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control,239^v3^insert_chatgpt"}} ] [.reference_item] - *2* *3* [java通过httpClient发送json格式数据请求(GET方式)](https://blog.csdn.net/xzj80927/article/details/127511924)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值