一下写法适用于一切接口的http形式的接口。包括单纯的http的接口,以及rest形式的接口。
需要的jar包:
httpclient-4.1.3.jar
httpcore-4.1.4.jar等
先来看一下post方式
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.HTTP
@Override
public String getEcifIdNew(ApplicationInfo applicationInfo) throws ClientProtocolException, IOException{
log.info("---------------开始********----------");
IcifParameter icifParame = new IcifParameter();//这是个接口传参定义的一个类,Post方式调用的时候一般是向服务端传递参数,做新增和修改以及删除相关的操作, //数据 已json字符串的形式传递
SimpleDateFormat dateFormater = new SimpleDateFormat("yyyyMMdd");
Date date=new Date();//下面的是一个接口中的参数,随机数以及日期和系统表示的参数
String format = dateFormater.format(date);
int[] array = {0,1,2,3,4,5,6,7,8,9};
Random rand = new Random();
for (int i = 10; i > 1; i--) {
int index = rand.nextInt(i);
int tmp = array[index];
array[index] = array[i - 1];
array[i - 1] = tmp;
}
int sixRandom = 0;
for(int i = 0; i < 6; i++)
sixRandom = sixRandom * 10 + array[i];
icifParame.setTransSn("PC003"+format+sixRandom);
icifParame.setSystemSign("03");
*************************
icifParame.setMobile(applicationInfo.getAppInfoMobile());
JSONObject jsonStu = JSONObject.fromObject(icifParame);
log.info("-------------参数-------------"+jsonStu.toString());
Properties properties = PropertiesUtil.loadProperties("spring/ecif/ecif.properties");
String url = properties.getProperty("ecif.url");//接口URL,从配置文件中读取的
HttpPost postMethod = new HttpPost(url);
StringEntity entity = new StringEntity(jsonStu.toString(), HTTP.UTF_8);
entity.setContentType("application/json");//固定写法
postMethod.setEntity(entity);
HttpClient client = new DefaultHttpClient();
HttpResponse response = client.execute(postMethod);
InputStream is = response.getEntity().getContent();
String result = new String(this.readInputStream(is).getBytes(),"UTF-8");
log.info("---------------获取ecifId结果:"+result);
return result;
}
public static String readInputStream(InputStream is) {
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int len = 0;
byte[] buffer = new byte[1024];
while ((len = is.read(buffer)) != -1) {
baos.write(buffer, 0, len);
}
is.close();
baos.close();
byte[] result = baos.toByteArray();
return new String(result);
} catch (Exception e) {
e.printStackTrace();
return "将输入流转化为字符串失败";
}
}
}
有一些用的时候可以作为工具类使用,基本上就是这样写的。
获得string返回值后,一般为json字符串,再做一下操作
JSONObject jsonObject2 = JSONObject.fromObject(result);//转化为json对象
String ecifIdResult2 = jsonObject2.getString("key").trim();//根据json对象中的key可以获得相应的value值
get方式的写法和post的基本上一样只是这里不一样:
HttpGet getMethod = new HttpGet(url.toString());//这个为get方式的。