java调用接口

a. pom添加依赖

junit
junit
3.8.1
test


org.apache.http
httpclient
4.4


org.apache.httpcomponents
httpcore
4.4.1


net.sf.json-lib
json-lib
2.4
jdk15

b. 调用接口,编写用例
、、、
package com.luck.auto.autoTest;

import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;

import javax.sql.DataSource;

import net.sf.json.JSONObject;

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.util.EntityUtils;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.mapping.Environment;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.apache.ibatis.transaction.TransactionFactory;
import org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory;
import org.junit.Assert;
import org.junit.Test;

import com.luck.auto.autoTest.dao.DbNoticeMapper;
import com.luck.auto.autoTest.domain.DbNotice;

/**

  • 类FirstTest.java的实现描述:TODO 类实现描述

  • @author jing 2017年3月19日 下午1:47:15
    */
    public class FirstTest {

    public JSONObject result = new JSONObject();
    public HttpResponse responseResult;
    public String postJson;
    public String resultStr;

@Test
public void firstTest() throws ClientProtocolException, IOException{
    //interface url
    String url="http://www.*********/account/login";  

    
    //request  json
    JSONObject jobj = new JSONObject();  
    jobj.put("Mobile", "********");  
    jobj.put("Password", "*******");  
    postJson = jobj.toString();
    //result
    responseResult = httpInlize(url,postJson);
    //response string formate
    resultStr = EntityUtils.toString(responseResult.getEntity()); 
    //response json formate
    result = result.fromObject(resultStr);
    System.out.print(resultStr.toString());

    Assert.assertEquals(200,responseResult.getStatusLine().getStatusCode());
    Assert.assertEquals("success",result.getString("status"));
    Assert.assertEquals("**********",result.getJSONObject("data").getString("Mobile"));
}

//http调用
public HttpResponse httpInlize(String url,String json) throws ClientProtocolException, IOException{
    StringEntity se = new StringEntity(json,"UTF-8");

    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost(url); 
    httppost.setEntity(se);
    httppost.setHeader("Content-type", "application/json; charset=utf-8");
    httppost.setHeader("Accept", "application/json");
    
    HttpResponse response = httpclient.execute(httppost);

// httppost.releaseConnection();

    return response;    

}
java调用接口_第1张图片
WangWang20170324012052.png

你可能感兴趣的:(java调用接口)