java代码发送ajax请求(post)

所需依赖

	
	    org.apache.httpcomponents
	    httpclient
	    4.5.2
	
	
	
	    commons-httpclient
	    commons-httpclient
	    3.0
	
	
	
	    org.apache.httpcomponents
	    httpcore
	    4.4.6
	
	
	
	    commons-beanutils
	    commons-beanutils
	    1.9.3
	
	
	
	    commons-codec
	    commons-codec
	    1.10
	
	
	
	    commons-collections
	    commons-collections
	    3.2.1
	
	
	
	    commons-lang
	    commons-lang
	    2.6
	
	
	
	    org.apache.commons
	    commons-lang3
	    3.4
	
	
	
	    commons-logging
	    commons-logging
	    1.1.1
	
/**
	* 只需要改一个url 和 data 参数  后面都不变都是固定的
	*/
	public static String getAccesstoken() {
		String result = null;
		// 请求地址
		String url = "https://eco.taobao.com/router/rest";
		//以集合的 传递值
		List<NameValuePair> parameForToken = new ArrayList<NameValuePair>();
		//data参数
		parameForToken.add(new BasicNameValuePair("appKey", "a5746267b1fa4d0489b643706236a8ac"));
		parameForToken.add(new BasicNameValuePair("appSecret", "aae7b3a877341a47bd5258dfd9bd2f18"));
		// 获取httpclient
		CloseableHttpClient httpclient = HttpClients.createDefault();
		CloseableHttpResponse response = null;
		try {
			// 创建post请求
			HttpPost httpPost = new HttpPost(url);
			// 设置请求和传输超时时间
			RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(2000).setConnectTimeout(2000).build();
			httpPost.setConfig(requestConfig);
	
			// 提交参数发送请求
			UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(parameForToken);
			httpPost.setEntity(urlEncodedFormEntity);
			response = httpclient.execute(httpPost);
			// 得到响应信息
			int statusCode = response.getStatusLine().getStatusCode();
			// 判断响应信息是否正确
			if (statusCode != HttpStatus.SC_OK) {
				// 终止并抛出异常
				httpPost.abort();
				throw new RuntimeException("HttpClient,error status code :" + statusCode);
			}
			HttpEntity entity = response.getEntity();
			if (entity != null) {
				// result = EntityUtils.toString(entity);//不进行编码设置
				result = EntityUtils.toString(entity, "UTF-8");
			}
			EntityUtils.consume(entity);
	
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			// 关闭所有资源连接
			if (response != null) {
				try {
					response.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (httpclient != null) {
				try {
					httpclient.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		String access=JSONObject.parseObject(JSONObject.parseObject(result).getString("data")).getString("accessToken");
		return access;
	}

你可能感兴趣的:(Java)