springboot模拟http发送url请求并处理返回结果的三种方法

本文介绍了在SpringBoot中使用RestTemplate, OkHttp和Apache HttpClient三种方式发送HTTP请求并处理返回结果。通过示例展示了如何使用这些库进行URL请求,并提供了获取响应数据的示例。" 106005995,9233845,Django框架下POST接口测试与JSON格式处理,"['Django', '接口测试']

RestTemplate方式

1.引入RestTemplate,

import org.springframework.web.client.RestTemplate;

1.直接拼接url.

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
public List<String> getHarborImageNames() {
        String uri = harborRepostitoryUrl+"api/repositories?project_id="+"2";
        System.out.println(uri);
        List<String> imageNames = new ArrayList<>();
        JSONArray result = restTemplate.getForObject(uri, JSONArray.class);
        for(Object object:result){
            JSONObject jsonObject = JSONObject.fromObject(object.toString());
            imageNames.add(jsonObject.getString("name"));
        }
        return imageNames;
    }
    //真实的url:https://ip:port/api/repositories?project_id=2
    //返回的结果无需封装在类里,则直接封装造json里,并从读取想要读取的内容。
    //// %7B:{  ,    %3D:=  ,  %22=" ,  %2C:,  ,      %7D:} ,  %20:空格   ,  %3D:=   ,  %5E:^   ,  %5B:[   ,  %5D:]  ,

2部分特殊字符直接拼接会报错,故有第二种方式

public List<String> getHarborTags2(String imageName) {
        //直接拼接?会报错 所以采取这种方式
        UriComponentsBuilder builder = UriComponentsBuilder
                .fromHttpUrl(this.harborRepostitoryUrl+"/api/repositories/test/"+imageName+"/tags").queryParam("detail", "true");
        URI url =builder.build(true).toUri();
        List<String> tags = new ArrayList<>();
        JSONArray result = restTemplate.getForObject(url, JSONArray.class);
        for(Object object:result){
            JSONObject jsonObject = JSONObject.fromObject(object.toString());
            tags.add(jsonObject.getString("name"));
        }
        return tags;
    }
    //真实的url为:https://harborIp:port/api/repositories/test/jifei-30_374/tags?detail=true

同样的返回读取的内容同样可以封装在其他类里面,该类里面的字段需要用户自己定义。具体例子将以另一种方式访问http连接来展示

okhttp方式

public List<Repository> getHarborImageNamesByProjectName(){
        Search search = null;
        try {
            search = harborClient.search("test");
            harborClient.logout();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (HarborClientException e) {
            e.printStackTrace();
        }
        if(search!=null & search.getRepository()!=null){
            List<Repository> repositories = search.getRepository();
            return repositories;
        }else{
            return null;
        }
    }
    
public Search search(String q) throws IOException, HarborClientException {
		String url = getBaseUrl() + "search?q=" + q;
		Request request = new Request.Builder().url(url).get().build();
		Response response = okhttpClient.newCall(request).execute();
		logger.debug(String.format(REQUEST_RESPONSE_INFO, request, response));
		if (response.code() != 200) {
			throw new HarborClientException(String.valueOf(response.code()), response.message());
		}
		return mapper.readValue(response.body().string(), Search.class);
	}

此种方式代码源公开在github上,有兴趣的人可以点击查看。https://github.com/johnnywong233/harbor-java-client

上述读取的内容如下:

[
{
“digest”: “sha256:1f152f479e36174ffaefae22efe9a6a1cef8a335fe09d3f45bdd8ac0df7ec06c”,
“name”: “v202002201552_11”,
“size”: 209997120,
“architecture”: “amd64”,
“os”: “linux”,
“os.version”: “”,
“docker_version”: “18.09.7”,
“author”: “”,
“created”: “2020-02-20T07:52:53.773559848Z”,
“config”: {
“labels”: null
},
“signature”: null,
“labels”: [],
“push_time”: “2020-02-20T07:52:57.535232Z”,
“pull_time”: “0001-01-01T00:00:00Z”
},
{
“digest”: “sha256:13c4ffda2427ef21183f67ef0f1f3e1adf4d5fdf89379e86ef195bdb285f0852”,
“name”: “v202002211832_16”,
“size”: 209998729,
“architecture”: “amd64”,
“os”: “linux”,
“os.version”: “”,
“docker_version”: “18.09.7”,
“author”: “”,
“created”: “2020-02-21T10:33:06.597565042Z”,
“config”: {
“labels”: null
},
“signature”: null,
“labels”: [],
“push_time”: “2020-02-21T10:33:10.722384Z”,
“pull_time”: “2020-02-21T10:33:40.690612Z”
},
{
“digest”: “sha256:990a51addf35176801cfd97fa19bb1df232c59ec2ca1eedd4b379d30d833e7ca”,
“name”: “v202002201040_4”,
“size”: 209997660,
“architecture”: “amd64”,
“os”: “linux”,
“os.version”: “”,
“docker_version”: “18.09.7”,
“author”: “”,
“created”: “2020-02-20T02:41:25.284960079Z”,
“config”: {
“labels”: null
},
“signature”: null,
“labels”: [],
“push_time”: “2020-02-20T02:41:30.183391Z”,
“pull_time”: “2020-02-20T02:42:26.410801Z”
},
{
“digest”: “sha256:d6854f4f51e4918269020017c129aca3ba402a1fec40e6cb85e6f821933c2403”,
“name”: “v202002201313_10”,
“size”: 209998343,
“architecture”: “amd64”,
“os”: “linux”,
“os.version”: “”,
“docker_version”: “18.09.7”,
“author”: “”,
“created”: “2020-02-20T05:13:29.693427451Z”,
“config”: {
“labels”: null
},
“signature”: null,
“labels”: [],
“push_time”: “2020-02-20T05:13:33.93381Z”,
“pull_time”: “2020-02-20T05:31:10.608007Z”
}
]

Appach httpClient方式

@RequestMapping(value = "/harbor/addProject", method = RequestMethod.POST)
    public JsonResponse<Boolean> addProject(HttpServletRequest httpRequest, @RequestBody Map<String, Object> params) throws Exception {
        UserInfo userInfo = UserUtil.getUserInfo(httpRequest);
        String projectName = MapUtil.getString(params,"projectName");
        String isPublic = MapUtil.getString(params,"isPublic");
        boolean result = repositoryService.addProject(userInfo,projectName,isPublic,userName,password,email);
        return new JsonResponse<Boolean>(result);
    }

public boolean addProject(String projectName, String isPublic){
		String adminAuth = "admin" + ":" + "Harbor12345";
        String authHeader = "Basic " + Base64.encodeBase64String(adminAuth.getBytes());
        String url =harborUrl+"projects";
        com.alibaba.fastjson.JSONObject proObj = new com.alibaba.fastjson.JSONObject();
        proObj.put("project_name", projectName);
        com.alibaba.fastjson.JSONObject metaObj = new com.alibaba.fastjson.JSONObject();
        metaObj.put("public", isPublic);
        metaObj.put("enable_content_trust", "true");
        metaObj.put("prevent_vul", "true");
        metaObj.put("severity", "low");
        metaObj.put("auto_scan", "true");
        proObj.put("metadata", metaObj);
        StringEntity stringEntity = new StringEntity(proObj.toJSONString(),"UTF-8");
        HttpPost httpPost = new HttpPost(url);
        httpPost.setEntity(stringEntity);
        httpPost.setHeader(HttpHeaders.AUTHORIZATION,authHeader);
        httpPost.setHeader("Content-Type", "application/json;charset=utf8");
        httpPost.setHeader("Accept","application/json");
        //本地下载证书后使用
        //CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        HttpResponse response = null;
        CloseableHttpClient httpClient = null;
        try {
        //实现无证书访问
            SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(
                    SSLContexts.custom().loadTrustMaterial(null,new TrustSelfSignedStrategy()).build(),
                    NoopHostnameVerifier.INSTANCE
            );
            httpClient = HttpClients.custom().setSSLSocketFactory(socketFactory).build();
            httpClient.execute(httpPost);
            return true;
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }

另外在附上处理response结果的方法

 public List<Project> getProjects() {
        String authHeader = "Basic " + Base64.encodeBase64String(adminAuth.getBytes());
        String url =harborUrl+"projects";

        HttpGet httpGet = new HttpGet(url);
        httpGet.setHeader(HttpHeaders.AUTHORIZATION,authHeader);
        httpGet.setHeader("Content-Type", "application/json;charset=utf8");
        httpGet.setHeader("Accept","application/json");
        //CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        HttpResponse response = null;
        CloseableHttpClient httpClient = null;
        try {
            SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(
                    SSLContexts.custom().loadTrustMaterial(null,new TrustSelfSignedStrategy()).build(),
                    NoopHostnameVerifier.INSTANCE
            );
            httpClient = HttpClients.custom().setSSLSocketFactory(socketFactory).build();
            response= httpClient.execute(httpGet);
        }catch (Exception e){
            e.printStackTrace();
        }
        System.out.println(response.getStatusLine().getStatusCode());
        String str = "";
        try {
            /**读取服务器返回过来的json字符串数据**/
            str = EntityUtils.toString(response.getEntity());
            //str = str.substring(1,str.length()-1);
            /**把json字符串转换成json对象**/
            System.out.println(str);
            //JSONObject jsonResult = JSONObject.fromObject(str);
            return mapper.readValue(str, new TypeReference<List<Project>>() {
            });
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

Project.calss


import com.fasterxml.jackson.annotation.*;

import javax.annotation.Generated;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by lyy on 2020/1/14.
 */
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(JsonInclude.Include.NON_NULL)
@Generated("org.jsonschema2pojo")
@JsonPropertyOrder({ "project_id", "owner_id", "name", "creation_time", "creation_time_str", "deleted", "owner_name",
		"public", "Togglable", "update_time", "current_user_role_id", "repo_count" })
public class Project {

	@JsonProperty("project_id")
	private Integer projectId;
	@JsonProperty("owner_id")
	private Integer ownerId;
	@JsonProperty("project_name")
	private String name;
	@JsonProperty("creation_time")
	private String creationTime;
	@JsonProperty("creation_time_str")
	private String creationTimeStr;
	@JsonProperty("deleted")
	private boolean deleted;
	@JsonProperty("owner_name")
	private String ownerName;
	@JsonProperty("public")
	private Object _public;
	@JsonProperty("update_time")
	private String updateTime;
	@JsonProperty("current_user_role_id")
	private Integer currentUserRoleId;
	@JsonProperty("repo_count")
	private Integer repoCount;
	@JsonIgnore
	private Map<String, Object> additionalProperties = new HashMap<String, Object>();

	/**
	 *
	 * @return The projectId
	 */
	@JsonProperty("project_id")
	public Integer getProjectId() {
		return projectId;
	}

	/**
	 *
	 * @param projectId
	 *            The project_id
	 */
	@JsonProperty("project_id")
	public void setProjectId(Integer projectId) {
		this.projectId = projectId;
	}

	/**
	 *
	 * @return The ownerId
	 */
	@JsonProperty("owner_id")
	public Integer getOwnerId() {
		return ownerId;
	}

	/**
	 *
	 * @param ownerId
	 *            The owner_id
	 */
	@JsonProperty("owner_id")
	public void setOwnerId(Integer ownerId) {
		this.ownerId = ownerId;
	}

	/**
	 *
	 * @return The name
	 */
	@JsonProperty("name")
	public String getName() {
		return name;
	}

	/**
	 *
	 * @param name
	 *            The name
	 */
	@JsonProperty("name")
	public void setName(String name) {
		this.name = name;
	}

	/**
	 *
	 * @return The creationTime
	 */
	@JsonProperty("creation_time")
	public String getCreationTime() {
		return creationTime;
	}

	/**
	 *
	 * @param creationTime
	 *            The creation_time
	 */
	@JsonProperty("creation_time")
	public void setCreationTime(String creationTime) {
		this.creationTime = creationTime;
	}

	/**
	 *
	 * @return The creationTimeStr
	 */
	@JsonProperty("creation_time_str")
	public String getCreationTimeStr() {
		return creationTimeStr;
	}

	/**
	 *
	 * @param creationTimeStr
	 *            The creation_time_str
	 */
	@JsonProperty("creation_time_str")
	public void setCreationTimeStr(String creationTimeStr) {
		this.creationTimeStr = creationTimeStr;
	}

	/**
	 *
	 * @return The deleted
	 */
	@JsonProperty("deleted")
	public boolean getDeleted() {
		return deleted;
	}

	/**
	 *
	 * @param deleted
	 *            The deleted
	 */
	@JsonProperty("deleted")
	public void setDeleted(boolean deleted) {
		this.deleted = deleted;
	}

	/**
	 *
	 * @return The ownerName
	 */
	@JsonProperty("owner_name")
	public String getOwnerName() {
		return ownerName;
	}

	/**
	 *
	 * @param ownerName
	 *            The owner_name
	 */
	@JsonProperty("owner_name")
	public void setOwnerName(String ownerName) {
		this.ownerName = ownerName;
	}

	/**
	 *
	 * @return The _public
	 */
	@JsonProperty("public")
	public Object getPublic() {
		return _public;
	}

	/**
	 *
	 * @param _public
	 *            The public
	 */
	@JsonProperty("public")
	public void setPublic(Object _public) {
		this._public = _public;
	}

	/**
	 *
	 * @return The updateTime
	 */
	@JsonProperty("update_time")
	public String getUpdateTime() {
		return updateTime;
	}

	/**
	 *
	 * @param updateTime
	 *            The update_time
	 */
	@JsonProperty("update_time")
	public void setUpdateTime(String updateTime) {
		this.updateTime = updateTime;
	}

	/**
	 *
	 * @return The currentUserRoleId
	 */
	@JsonProperty("current_user_role_id")
	public Integer getCurrentUserRoleId() {
		return currentUserRoleId;
	}

	/**
	 *
	 * @param currentUserRoleId
	 *            The current_user_role_id
	 */
	@JsonProperty("current_user_role_id")
	public void setCurrentUserRoleId(Integer currentUserRoleId) {
		this.currentUserRoleId = currentUserRoleId;
	}

	/**
	 *
	 * @return The repoCount
	 */
	@JsonProperty("repo_count")
	public Integer getRepoCount() {
		return repoCount;
	}

	/**
	 *
	 * @param repoCount
	 *            The repo_count
	 */
	@JsonProperty("repo_count")
	public void setRepoCount(Integer repoCount) {
		this.repoCount = repoCount;
	}

	@JsonAnyGetter
	public Map<String, Object> getAdditionalProperties() {
		return this.additionalProperties;
	}

	@JsonAnySetter
	public void setAdditionalProperty(String name, Object value) {
		this.additionalProperties.put(name, value);
	}

	@Override
	public String toString() {
		return "Project{" + "projectId=" + projectId + ", ownerId=" + ownerId + ", name='" + name + '\''
				+ ", creationTime='" + creationTime + '\'' + ", creationTimeStr='" + creationTimeStr + '\''
				+ ", deleted=" + deleted + ", ownerName='" + ownerName + '\'' + ", _public=" + _public + '\''
				+ ", updateTime=" + updateTime + '\'' + ", currentUserRoleId=" + currentUserRoleId
				+ ", repoCount=" + repoCount + ", additionalProperties=" + additionalProperties + '}';
	}
}

以上,多多学习交流。主要是利用http连接访问普罗米修斯和harbor仓库并返回需要的数据。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值