欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

java使用common-httpclient包实现post请求方法示例

程序员文章站 2024-02-21 12:12:28
前言 项目中需要请求第三方接口,而且要求请求参数数据为json类型的。本来首先使用的是httpclient的jar包,但是因为项目中已经使用了common-httpcli...

前言

项目中需要请求第三方接口,而且要求请求参数数据为json类型的。本来首先使用的是httpclient的jar包,但是因为项目中已经使用了common-httpclient的jar包,引起了冲突,所以不得不使用common-httpclient来实现。

示例代码:

import java.io.bufferedreader;
import java.io.fileoutputstream;
import java.io.ioexception;
import java.io.inputstream;
import java.io.inputstreamreader;
import java.net.url;
import java.net.urlconnection;
import java.util.list;
import java.util.map;
import java.util.zip.gzipinputstream;

import org.apache.commons.httpclient.httpclient;
import org.apache.commons.httpclient.httpmethod;
import org.apache.commons.httpclient.namevaluepair;
import org.apache.commons.httpclient.methods.getmethod;
import org.apache.commons.httpclient.methods.postmethod;
import org.apache.commons.httpclient.methods.requestentity;
import org.apache.commons.httpclient.methods.stringrequestentity;
import org.apache.commons.io.ioutils;
import org.slf4j.logger;
import org.slf4j.loggerfactory;


public class httputils {

 private static logger logger = loggerfactory.getlogger(httputils.class);

 /**
  * post请求
  * @param url
  * @param json
  * @return
  */
 public static string postjosncontent(string url, string json) throws exception {
//  httppost method = new httppost(url); 
//  defaulthttpclient httpclient = new defaulthttpclient(); 
//  string ret = null;
//  try {
//   stringentity entity = new stringentity(json,"utf-8");//解决中文乱码问题  
//    entity.setcontentencoding("utf-8"); 
//    entity.setcontenttype("application/json");
//    method.setentity(entity); 
//    httpresponse result = httpclient.execute(method); 
//    ret = entityutils.tostring(result.getentity()); 
//  } catch (exception e) {
//   throw e;
//  } finally {
//   method.releaseconnection();
//  }
//  return ret;
  logger.error("请求接口参数:" + json);
  postmethod method = new postmethod(url);
  httpclient httpclient = new httpclient();
  try {
   requestentity entity = new stringrequestentity(json,"application/json","utf-8");
   method.setrequestentity(entity);
   httpclient.executemethod(method);
   logger.error("请求接口路径url:" + method.geturi().tostring());
   inputstream in = method.getresponsebodyasstream();
   //下面将stream转换为string
   stringbuffer sb = new stringbuffer();
   inputstreamreader isr = new inputstreamreader(in, "utf-8");
   char[] b = new char[4096];
   for(int n; (n = isr.read(b)) != -1;) {
    sb.append(new string(b, 0, n));
   }
   string returnstr = sb.tostring();
   return returnstr;
  } catch (exception e) {
   e.printstacktrace();
   throw e;
  } finally {
   method.releaseconnection();
  }
 }
}

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对的支持。