java访问http和https的方法

1 通过url进行访问

/**
 * 使用URL类进行访问http和https
 */
public class URLTest {
	public static void main(String[] args) {
//		String https2="https://www.apiopen.top/journalismApi";
		String https="https://api.weixin.qq.com/sns/oauth2/access_token?appid=appid&code=code&grant_type=authorization_code";
		InputStream in=null;
		try {
			URL url=new URL(https);
			HttpsURLConnection openConnection = (HttpsURLConnection) url.openConnection();
			String protocol = url.getProtocol();
			System.out.println(protocol);
			openConnection.connect();
  			in = openConnection.getInputStream();
  			
			StringBuilder builder=new StringBuilder();
			BufferedReader bufreader =new BufferedReader(new InputStreamReader(in));
			for (String temp=bufreader.readLine();temp!=null;temp= bufreader.readLine()) {
				builder.append(temp);
			}
			System.out.println(builder);
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}finally {
			try {
				in.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}

访问结果:

https
{"errcode":41004,"errmsg":"appsecret missing, hints: [ req_id: ODkxIA06672030 ]"}

2 通过httpClient进行访问

/**
 * 使用HttpClient来访问https和http
 * 注意:url地址中不能有null格,不然会报错
 */
public class HttpsTest {
	public static void main(String[] args) {
		CloseableHttpClient client = HttpClients.createDefault();
		String url="https://www.apiopen.top/journalismApi";
		HttpGet get=new HttpGet(url);
		try {
			CloseableHttpResponse execute = client.execute(get);
			HttpEntity entity = execute.getEntity();
			InputStream in = entity.getContent();
			StringBuilder builder=new StringBuilder();
			BufferedReader bufreader =new BufferedReader(new InputStreamReader(in));
			for (String temp=bufreader.readLine();temp!=null;temp= bufreader.readLine()) {
				builder.append(temp);
			}
			System.out.println(builder.toString());
		} catch (ClientProtocolException e) {
			throw new RuntimeException(e);
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}
}

使用httpclient的pom依赖:

	    <dependency>
	 		<groupId>org.apache.httpcomponents</groupId>
			<artifactId>httpclient</artifactId>
			<version>4.5.5</version>
		</dependency>

3 不删除null格会报错

猜你喜欢

转载自blog.csdn.net/qq_39729527/article/details/81352983