使用Client调用三方的RestAPI

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/liyaohui_szz/article/details/81132228

1、post方式(json和表单)访问http的rest接口

(1)json的形式post数据 

Headers为:content-type:application/json 
Body:{key1:value1, key2:value2, key3:value3}
   /**
     * 以json的形式提交数据
     * @param url
     * @param obj
     * @return
     */
    public static String httpPost(String url, JSONObject obj) {
        String _encoding = "UTF-8";
        StringBuffer sb = new StringBuffer();
        BufferedReader in = null;

        HttpClient client = new DefaultHttpClient();
        HttpPost post = new HttpPost(url);
        try {
            StringEntity entity = new StringEntity(obj.toString(),"utf-8");//解决中文乱码问题    
            entity.setContentEncoding("UTF-8");    
            entity.setContentType("application/json");    
            post.setEntity(entity);    
            System.out.println("getRequestLine:" + post.getRequestLine());

            // 执行请求
            HttpResponse response = client.execute(post);
            in = new BufferedReader(new InputStreamReader(response.getEntity()
                    .getContent(), _encoding));
            String line = "";
            String NL = System.getProperty("line.separator");
            while ((line = in.readLine()) != null) {
                sb.append(line + NL);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e1) {
                }
            }
            // 关闭连接.
            try {
                client.getConnectionManager().shutdown();
            } catch (Exception e1) {
            }
        }
        String str = "";
        try {
            str = sb.toString();
        } catch (Exception e) {

        }
        return str; 
    }

测试:

 public static void main(String[] args) throws Exception {      
        String api = "http://localhost:7080/api";
        String str = "{accessToken:'aa',expiresIn:7200,createTime:1234566,flag:1,appId:111111111}";
        JSONObject obj = JSONObject.fromObject(str);
        String content = HttpClientUtil.httpPost1(api + "/token" , obj);
        System.out.println( content);
    }

(2)表单的形式post数据 

public static String getJsonString(String url, String xm, String zjhm, String reqid, String ywtype, String oc,
			String appkey) {
		HttpPost httpPost = null;
		try {
			CloseableHttpClient httpClient = HttpClients.createDefault();
			httpPost = new HttpPost(url);
			RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(30000).setConnectTimeout(30000)
					.build();// 设置请求和传输超时时间
			httpPost.setConfig(requestConfig);
			List<NameValuePair> list = new ArrayList<NameValuePair>();
			//String xm1 = URLEncoder.encode(xm, "UTF-8");
			//String zjhm1 = URLEncoder.encode(zjhm, "UTF-8");
			list.add(new BasicNameValuePair("xm", xm));
			list.add(new BasicNameValuePair("zjhm", zjhm));
			list.add(new BasicNameValuePair("reqid", reqid));
			list.add(new BasicNameValuePair("ywtype", ywtype));
			list.add(new BasicNameValuePair("oc", oc));
			list.add(new BasicNameValuePair("appkey", appkey));
			UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, "utf-8");
			httpPost.setEntity(entity);
			HttpResponse response = httpClient.execute(httpPost);
			if (response != null) {

				HttpEntity resEntity = response.getEntity();
				if (resEntity != null) {
					return EntityUtils.toString(resEntity, "utf-8");
				}
			}
		} catch (Exception e) {
			e.printStackTrace();

		} finally {
			httpPost.releaseConnection();
		}
		return "";

	}

测试:

	public static void main(String[] args) throws UnsupportedEncodingException {
		// TODO Auto-generated method stub
		String result = xjbysfzxx.getJsonString("http://59.255.68.74/cegn/xjbysfzh", "xx","","xx", "xx","xx", "xx");
		System.out.println(result);
	}

2、get方式访问http的rest接口

 /**
     * 以get的方式访问http的rest接口
     * @param url
     * @return
     * @throws Exception
     */
      public static String httpGet(String url) throws Exception {  
        BufferedReader in = null;  
        String content = null;  
        try {  
            // 定义HttpClient  
            HttpClient client = new DefaultHttpClient();  
            // 实例化HTTP方法  
            HttpGet request = new HttpGet();  
            request.setURI(new URI(url));  
            HttpResponse response = client.execute(request);  

            in = new BufferedReader(new InputStreamReader(response.getEntity()  
                    .getContent()));  
            StringBuffer sb = new StringBuffer("");  
            String line = "";  
            String NL = System.getProperty("line.separator");  
            while ((line = in.readLine()) != null) {  
                sb.append(line + NL);  
            }  
            in.close();  
            content = sb.toString();  
        } finally {  
            if (in != null) {  
                try {  
                    in.close();// 最后要关闭BufferedReader  
                } catch (Exception e) {  
                    e.printStackTrace();  
                }  
            }  
            return content;  
        }  
    }  

测试:

 public static void main(String[] args) throws Exception {       
        String api = "http://localhost:7080/api";
        String content = HttpClientUtil.httpGet(api + "/getUser?username=hello" );
        System.out.println( content);
    }

猜你喜欢

转载自blog.csdn.net/liyaohui_szz/article/details/81132228