Java代码连接web服务器

这一期,将利用apache旗下的开源项目Apache HttpComponents实现Java代码连接web服务器,该项目的官方地址为http://hc.apache.org,该项目还有很多功能,本篇只给出最常用的例子,不多说直接上代码吧。

package my;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.StatusLine;
import org.apache.http.client.CookieStore;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;

public class MyClient
{

	/**
	 * get方式请求
	 */
	public static void getDemo()
	{
		//样访问的地址
		String url = "http://127.0.0.1:8080/demo";
		
		//创建HTTP客户端
		CloseableHttpClient httpclient;
		int timeout = 3000;
		CookieStore cookieStore = new BasicCookieStore();
		httpclient = HttpClients.custom().setDefaultCookieStore(cookieStore).build();
		
		// 创建HTTP请求
		RequestConfig requestConfig = RequestConfig.custom()
				.setSocketTimeout(timeout) 
				.setConnectTimeout(timeout) 
				.build();
		
		//附加参数
		List<NameValuePair> nvps = new ArrayList<>();
		nvps.add(new BasicNameValuePair("id" , "20190001"));
		nvps.add(new BasicNameValuePair("major" , "数学"));
		String query = URLEncodedUtils.format(nvps, "UTF-8");
		url = url + "?" + query;
		
		//创建get的请求
		HttpGet httpget = new HttpGet(url);
		httpget.setConfig(requestConfig);
	
		try
		{			
			//执行HTTp清求,得到应答
			System.out.println(">>" + url);
			CloseableHttpResponse response = httpclient.execute(httpget);
			//查看相应结果
			StatusLine ststusLine = response.getStatusLine();
			//获取状态码
			int status = ststusLine.getStatusCode();
			if(status != 200)
			{
				System.out.println("访问出现问题,状态码为:" + status);
			}
			else
			{
				HttpEntity dataRecv = response.getEntity();
				String content = EntityUtils.toString(dataRecv);
				System.out.println(content);
			}
			response.close();
		} catch (IOException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	
	}
	//post请求,以表单的方式提交数据
	public static void postTest1()
	{
		String url = "http://127.0.0.1:8080/demo";
		CloseableHttpClient httpClient;
		int timeout = 3000;	
		CookieStore cookieStore = new BasicCookieStore();
		
		httpClient = HttpClients.custom()
				.setDefaultCookieStore(cookieStore)
				.build();
		
		RequestConfig requestConfig = RequestConfig.custom()
				.setSocketTimeout(timeout)
				.setConnectTimeout(timeout)
				.build();
		HttpPost httpost = new HttpPost(url);
		httpost.setConfig(requestConfig);
		// 要上传的参数
		List <NameValuePair> nvps = new ArrayList <>();
		nvps.add(new BasicNameValuePair("username", "小明"));		
		nvps.add(new BasicNameValuePair("password", "123456"));
		UrlEncodedFormEntity entity = new UrlEncodedFormEntity(nvps , Consts.UTF_8);
		httpost.setEntity(entity);
		//执行post请求,得到回答
		try
		{
			CloseableHttpResponse response = httpClient.execute(httpost);
			//查看应答结果
			StatusLine statusLine = response.getStatusLine();
			int status = statusLine.getStatusCode();
			if(status != 200)
			{
				System.out.println("访问服务器出现问题,状态码为:" + status);
			}
			else
			{
				HttpEntity entity1 = response.getEntity();
				String content = EntityUtils.toString(entity1);
				System.out.println(">>" + content);
			}
		} catch (IOException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	//post请求,以json格式传输
	public static void postTest2()
	{
		String url = "http://127.0.0.1:8080/demo";
		CloseableHttpClient httpClient;
		int timeout = 3000;	
		CookieStore cookieStore = new BasicCookieStore();
		
		httpClient = HttpClients.custom()
				.setDefaultCookieStore(cookieStore)
				.build();
		
		RequestConfig requestConfig = RequestConfig.custom()
				.setSocketTimeout(timeout)
				.setConnectTimeout(timeout)
				.build();
		HttpPost httpost = new HttpPost(url);
		httpost.setConfig(requestConfig);
		// 要上传的参数
		// 要上传的参数
		JSONObject jreq = new JSONObject();
		jreq.put("username", "小明");
		jreq.put("password", "123456");
		// JSON / RESTful 方式, Content Type 可以为 text/plain
		StringEntity entity = new StringEntity(jreq.toString(), Consts.UTF_8);		
		entity.setContentType("text/plain");
		httpost.setEntity(entity);	
		//执行post请求,得到回答
		try
		{
			CloseableHttpResponse response = httpClient.execute(httpost);
			//查看应答结果
			StatusLine statusLine = response.getStatusLine();
			int status = statusLine.getStatusCode();
			if(status != 200)
			{
				System.out.println("访问服务器出现问题,状态码为:" + status);
			}
			else
			{
				HttpEntity entity1 = response.getEntity();
				String content = EntityUtils.toString(entity1);
				System.out.println(">>" + content);
			}
		} catch (IOException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	public static void main(String[] args)
	{
		// TODO Auto-generated method stub
		//getDemo();
		//postTest1();
		postTest2();

	}

}

 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

AndyWei147

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值