HttpGet请求的几种方式(自用勿喷)

HttpClient

参数拼接到链接后的HttpGet请求

	@Override
	public Object priceCalculation(AssetStore asset) {
        // 需要取价格
		Object price = asset.getPrice();
		HttpClient httpClient = null;
		String result = null;
		try {
			httpClient = new SSLClient();
			HttpGet httpGet = new HttpGet("https://请求链接?参数1=" + 值1 + "&参数2=" + 值2);
			HttpResponse response = httpClient.execute(httpGet);
			if (response != null) {
				HttpEntity resEntity = response.getEntity();
				if (resEntity != null) {
					result = EntityUtils.toString(resEntity, "utf-8");
					JSONObject pa = JSONObject.parseObject(result);
					if (pa.get("code").equals(200)) {
						String data = pa.getString("data");
                        // 返回值
						JSONObject pa1 = JSONObject.parseObject(data);
                        // 取价格
						price = pa1.get("discountedPrice");
					}
				}
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		}
        return price;
	}

 无参数,传递Headers的HttpGet请求

// 获取用户名称	
public String userinfo(String ssoToken, String name) {
		HttpClient httpClient = null;
		String result = null;
		String userName = null;
		try {
			httpClient = new SSLClient();
			HttpGet httpGet = new HttpGet("https://请求链接");
			httpGet.addHeader("Content-Type", "application/json");
			httpGet.addHeader("User-Agent", name);
			httpGet.addHeader("Authorization",
					"Bearer " + ssoToken);
			HttpResponse response = httpClient.execute(httpGet);
			if (response != null) {
				HttpEntity resEntity = response.getEntity();
				if (resEntity != null) {
					result = EntityUtils.toString(resEntity, "utf-8");
					JSONObject pa = JSONObject.parseObject(result);
					if (pa.getString("realname") != null) {
						userName = pa.getString("realname");
					} else if (pa.getString("username") != null) {
						userName = pa.getString("username");
					} else if (pa.getString("nickname") != null) {
						userName = pa.getString("nickname");
					} else {
						userName = "名称";
					}
				}
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return userName;
	}

你可能感兴趣的:(java,servlet,json)