httpclient 使用方式介绍

第一:Get方式请求

package com.hct;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONObject;

public class GetPort {

	public static JSONObject getUrl(String url) throws ClientProtocolException, IOException {
		 // 创建HttpClient实例     
        DefaultHttpClient httpclient = new DefaultHttpClient(); 
        JSONObject son = new JSONObject();
        // 创建Get方法实例     
        HttpGet httpgets = new HttpGet(url);    
        HttpResponse response = httpclient.execute(httpgets);    
        HttpEntity entity = response.getEntity();    
        if (entity != null) {    
            InputStream instreams = entity.getContent();    
            String str = convertStreamToString(instreams); 
            son = new JSONObject(str);
            System.out.println("以下是响应结果:");   
            System.out.println(str); 
            // Do not need the rest    
            httpgets.abort();    
        }  
        return son;
    }  
      
    public static String convertStreamToString(InputStream is) {      
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));      
        StringBuilder sb = new StringBuilder();      
       
        String line = null;      
        try {      
            while ((line = reader.readLine()) != null) {  
                sb.append(line + "
");      
            }      
        } catch (IOException e) {      
            e.printStackTrace();      
        } finally {      
            try {      
                is.close();      
            } catch (IOException e) {      
               e.printStackTrace();      
            }      
        }      
        return sb.toString();      
	}

}

第二:post请求方式

package com.hct;

import java.io.IOException;
import java.util.Map;

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.json.JSONObject;

public class PostPort {

	public JSONObject postResponse(String url,String json,Map<String, String> headers) throws ClientProtocolException, IOException {
		HttpClient httpclient = new DefaultHttpClient();
		String uri = url;
		HttpPost httppost = new HttpPost(uri);
		if(!headers.isEmpty()){
			for(String key : headers.keySet())
			{
				// 遍历map对象添加http头信息
				httppost.addHeader(key, headers.get(key)); 
			}
		}
		JSONObject parameters = new JSONObject(json);
		//将参数添加进请求url中
		httppost.setEntity(new StringEntity(parameters.toString()));
		
		HttpResponse response;
		//执行请求
		response = httpclient.execute(httppost);
		//获取状态码
		int t = response.getStatusLine().getStatusCode();
		if(t==200){
			String rev = EntityUtils.toString(response.getEntity());
			System.out.println(rev);
			parameters =new JSONObject(rev);
		/*	测试使用
			String orderId = (String) parameters.get("orderId"); 
			System.out.println(orderId);*/
			
		}
		return parameters;
	}
	
	public JSONObject postResponse1(String url,String json) throws ClientProtocolException, IOException{
		String uri =url;
		String para = json;
		JSONObject jso = null;
		jso = postResponse(uri, para, null);
		return jso;
		
		
	}
	
}

第三:使用testng进行测试

package com.hct118;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import org.apache.http.client.ClientProtocolException;
import org.json.JSONObject;
import org.testng.Assert;
import org.testng.annotations.Test;


public class TestPortCase {
  //核保接口测试
  @Test
  public void testPost() throws ClientProtocolException, IOException {
		String uri = "http://10.253.10.226:8080/invest/mvc/m/clients/underwriter";
		Map<String, String> map = new HashMap<String, String>();
		map.put("token", "9802525003ff40d1a39863722371f8c1");
		map.put("Content-Type", "application/json");
		String json = "{"phoneNo":18234560012,
" + 
				""tradeAccount":"test8887",
" + 
				""name":"谭宝玲",
" + 
				""certNo":"440681198610152044",
" + 
				""amount":"40000.11",
" + 
				""channelRequestNo":"test00044442",
" + 
				""productOffingCode":"101001048364"
" + 
				"}";
		PostPort pp = new PostPort();
		JSONObject jso = pp.postResponse(uri, json, map);
		System.out.println(jso.get("channelOrderNo"));
		Assert.assertEquals(jso.get("returnMsg"), "成功");
  }
  @Test
  public void testGet() throws ClientProtocolException, IOException
  {
	  String url = "http://10.253.10.226:8080/invest/mvc/commons/sms/otp/new?phoneNo=18234560012&token=9802525003ff40d1a39863722371f8c1";
	  JSONObject js =  GetPort.getUrl(url);
	  Assert.assertEquals(js.get("status"), "SUCCESS");
  }
  
}

  

原文地址:https://www.cnblogs.com/HCT118/p/5989013.html