httpclient提交json参数的示例详解

 更新时间:2024年02月03日 09:32:25   作者:有一只柴犬  
httpclient使用post提交json参数,和使用表单提交区分,本文结合示例代码讲解的非常详细,补充介绍了HttpClient请求传json参数的案例代码,感兴趣的朋友一起看看吧

httpclient提交json参数

httpclient使用post提交json参数,(跟使用表单提交区分):

private void httpReqUrl(List<HongGuTan> list, String url)
			throws ClientProtocolException, IOException {
		logger.info("httpclient执行新闻资讯接口开始。");
		JSONObject json = new JSONObject();
		DefaultHttpClient httpClient = new DefaultHttpClient();
		HttpPost method = new HttpPost(url);
		// 设置代理
		if (IS_NEED_PROXY.equals("1")) {
			HttpHost proxy = new HttpHost("192.168.13.19", 7777);
			httpClient.getParams().setParameter(ConnRouteParams.DEFAULT_PROXY, proxy);
		}
		if (list != null && list.size() > 0) {
			logger.info("循环处理数据列表大小list.size={}", list != null ? list.size() : 0);
			// 开始循环组装post请求参数,使用倒序进行处理
			for (int i = list.size() - 1; i >= 0; i--) {
				HongGuTan bean = list.get(i);
				if (bean == null) {
					continue;
				}
				// 验证参数
				Object[] objs = { bean.getTitle(), bean.getContent(),
						bean.getSourceUrl(), bean.getSourceFrom(),
						bean.getImgUrls() };
				if (!validateData(objs)) {
					logger.info("参数验证有误。");
					continue;
				}
				// 接收参数json列表
				JSONObject jsonParam = new JSONObject();
				jsonParam.put("chnl_id", "11");// 红谷滩新闻资讯,channelId 77
				jsonParam.put("title", bean.getTitle());// 标题
				jsonParam.put("content", bean.getContent());// 资讯内容
				jsonParam.put("source_url", bean.getSourceUrl());// 资讯源地址
				jsonParam.put("source_name", bean.getSourceFrom());// 来源网站名称
				jsonParam.put("img_urls", bean.getImgUrls());// 采用 url,url,url 的格式进行图片的返回
				StringEntity entity = new StringEntity(jsonParam.toString(),"utf-8");//解决中文乱码问题  
				entity.setContentEncoding("UTF-8");  
				entity.setContentType("application/json");  
				method.setEntity(entity);  
				//这边使用适用正常的表单提交 
//				 List<BasicNameValuePair> pairList = new ArrayList<BasicNameValuePair>();  
				//pairList.add(new BasicNameValuePair("chnl_id", "11")); 
				//pairList.add(new BasicNameValuePair("title", bean.getTitle()));// 标题  
				//pairList.add(new BasicNameValuePair("content", bean.getContent()));// 资讯内容  
				//pairList.add(new BasicNameValuePair("source_url", bean.getSourceUrl()));// 资讯源地址  
				//pairList.add(new BasicNameValuePair("source_name", bean.getSourceFrom()));// 来源网站名称  
				//pairList.add(new BasicNameValuePair("img_urls", bean.getImgUrls()));// 采用 url,url,url 的格式进行图片的返回  
				//method.setEntity(new UrlEncodedFormEntity(pairList, "utf-8")); 
				HttpResponse result = httpClient.execute(method);
				// 请求结束,返回结果
				String resData = EntityUtils.toString(result.getEntity());
				JSONObject resJson = json.parseObject(resData);
				String code = resJson.get("result_code").toString(); // 对方接口请求返回结果:0成功  1失败
				logger.info("请求返回结果集{'code':" + code + ",'desc':'" + resJson.get("result_desc").toString() + "'}");
				if (!StringUtils.isBlank(code) && code.trim().equals("0")) {// 成功
					logger.info("业务处理成功!");
				} else {
					logger.error("业务处理异常");
					Constants.dateMap.put("lastMaxId", bean.getId());
					break;
				}
			}
		}
	}

补充:

HttpClient请求传json参数

http请求,参数为json字符串

public String setMessage(String requestData) {
		String result = "";
		try {
			result = HttpClientUtils.doPost(url, method, requestData);
		} catch (ClientProtocolException e) {
			e.printStackTrace();
			throw new ValidationException(SystemError.CONNECTION_FAIL);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return result;    }

HttpClientUtils工具类

package com.feeling.mc.agenda.util;
import java.io.IOException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
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.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import net.logstash.logback.encoder.org.apache.commons.lang.StringUtils;
/**
 * 使用
 * @author liangwenbo
 *
 */
@SuppressWarnings({ "resource", "deprecation" })
public class HttpClientUtils {
	public static String doGet(String url,String params) throws ClientProtocolException, IOException {
		String response = null;
		HttpClient httpClient = new DefaultHttpClient();
		HttpGet httpGet = new HttpGet(url);
		HttpResponse httpResponse = httpClient.execute(httpGet);
		if (httpResponse.getStatusLine().getStatusCode() == 200) {
			// 请求和响应都成功了
			HttpEntity entity = httpResponse.getEntity();// 调用getEntity()方法获取到一个HttpEntity实例
			response = EntityUtils.toString(entity, "utf-8");// 用EntityUtils.toString()这个静态方法将HttpEntity转换成字符串,防止
																// //服务器返回的数据带有中文,所以在转换的时候将字符集指定成utf-8就可以了
		}
		return response;
	}
	/**
	 * localhost:8091/message
	 * @param url http:localhost:8080
	 * @param method 方法
	 * @return params 参数
	 * @throws ClientProtocolException
	 * @throws IOException
	 */
	public static String doPost(String url, String method, String params) throws ClientProtocolException, IOException {
		String response = null;
		String sendUrl = url+method;
		HttpClient httpClient = new DefaultHttpClient();
		HttpPost httpPost = new HttpPost(sendUrl);
		 if (StringUtils.isNotBlank(params)) {
			 httpPost.setEntity(new StringEntity(params, "utf-8"));
	     }
		HttpResponse httpResponse = httpClient.execute(httpPost); 
		if (httpResponse.getStatusLine().getStatusCode() == 200) {
			// 请求和响应都成功了
			HttpEntity entity = httpResponse.getEntity();// 调用getEntity()方法获取到一个HttpEntity实例
			response = EntityUtils.toString(entity, "utf-8");// 用EntityUtils.toString()这个静态方法将HttpEntity转换成字符串,防止
																// //服务器返回的数据带有中文,所以在转换的时候将字符集指定成utf-8就可以了
		}
		return response;
	}
}

到此这篇关于httpclient提交json参数的文章就介绍到这了,更多相关httpclient提交json参数内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • Java实现微信公众号获取临时二维码功能示例

    Java实现微信公众号获取临时二维码功能示例

    这篇文章主要介绍了Java实现微信公众号获取临时二维码功能,结合实例形式分析了java调用微信公众号接口实现临时二维码生成功能相关操作技巧,需要的朋友可以参考下
    2019-10-10
  • 简单易懂的Java Map数据添加指南

    简单易懂的Java Map数据添加指南

    Java提供了多种方法来往Map中添加数据,开发者可以根据具体需求选择合适的方法,需要的朋友可以参考下
    2023-11-11
  • Java泛型extends关键字设置边界的实现

    Java泛型extends关键字设置边界的实现

    这篇文章主要介绍了Java泛型extends关键字设置边界的实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2019-09-09
  • Java实现消消乐中的消除功能

    Java实现消消乐中的消除功能

    这篇文章主要为大家详细介绍了Java实现消消乐中的消除功能,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2021-07-07
  • spring学习JdbcTemplate数据库事务管理

    spring学习JdbcTemplate数据库事务管理

    这篇文章主要为大家介绍了spring学习JdbcTemplate数据库事务管理,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2022-05-05
  • Spring利用注解整合Mybatis的方法详解

    Spring利用注解整合Mybatis的方法详解

    这篇文章主要为大家介绍了Spring如何利用注解整合MyBatis,文中的示例代码讲解详细,对我们学习有一定的参考价值,需要的小伙伴可以参考一下
    2022-06-06
  • Java 流的高级使用之收集数据解析

    Java 流的高级使用之收集数据解析

    这篇文章主要介绍了Java 流的高级使用之收集数据解析,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2021-08-08
  • 解决IntelliJ IDEA创建spring boot无法连接http://start.spring.io/问题

    解决IntelliJ IDEA创建spring boot无法连接http://start.spring.io/问题

    这篇文章主要介绍了解决IntelliJ IDEA创建spring boot无法连接http://start.spring.io/问题,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2020-08-08
  • Java单链表反转图文教程

    Java单链表反转图文教程

    这篇文章主要给大家介绍了关于Java单链表反转的相关资料,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2021-04-04
  • java 多线程Thread与runnable的区别

    java 多线程Thread与runnable的区别

    这篇文章主要介绍了java 多线程Thread与runnable的区别的相关资料,java线程有两种方法继承thread类与实现runnable接口,下面就提供实例帮助大家理解,需要的朋友可以参考下
    2017-08-08

最新评论