java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > httpclient提交json参数

httpclient提交json参数的示例详解

作者:有一只柴犬

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参数内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文