Explain in detail that Java sends HTTP requests

  • 2021-07-13 05:23:18
  • OfStack

Preface

The Demo requesting http has been personally tested, and this mode has been running online at present. Because it is an http request, all demo that send post and get requests are posted below, including how to test them. You can use copy directly in your own project.

Text

Instructions for use

In order to avoid everyone leading the wrong package, I will give you the dependency and the package path involved


import java.net.HttpURLConnection;
import java.net.URI;
 
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
 
 
import com.fasterxml.jackson.databind.ObjectMapper;

 <dependency>
			<groupId>org.apache.httpcomponents</groupId>
			<artifactId>httpcore</artifactId>
			<version>4.4.8</version>
		</dependency>
		<dependency>
			<groupId>org.apache.httpcomponents</groupId>
			<artifactId>httpclient</artifactId>
			<version>4.5.3</version>
		</dependency>

HTTP sends get request

First, we introduce two packages

The tool class for sending get request can be used directly by copy

In addition, I throw exception code everyone changed to their own business exception, do not need to delete.

Parameter description:

host: ip

servUri: url

reString: Parameters


public static String getHttpData(String host, String servUri, String reString) throws Exception {
		StringBuffer sb = new StringBuffer();
		sb.append("getHttpData:host:" + host + ",servUri:" + servUri + ",reString:" + reString);
		String strResp = null;
		try {
			URI uri = new URIBuilder().setScheme("http").setHost(host).setPath(servUri)
					.setParameter("strInfo", reString).build();
			HttpGet httpGet = new HttpGet(uri);
			CloseableHttpClient client3 = HttpClients.createDefault();
			HttpResponse resp;
			resp = client3.execute(httpGet);
			if (resp.getStatusLine().getStatusCode() == HttpURLConnection.HTTP_OK) {
				strResp = EntityUtils.toString(resp.getEntity());
				logger.info("the return result:{}", strResp);
			} else {
				logger.info("Error Response:", resp.getStatusLine().toString());
				throw new CommonBusinessException(CommonConstants.TASK_RELEASE_WCF,
						CommonConstants.TASK_RELEASE_WCF_DESC);
			}
		} catch (Exception e) {
			logger.error(sb.toString() + ":" + e.getMessage(), e.getCause());
			throw new CommonBusinessException(CommonConstants.TASK_RELEASE_WCF, CommonConstants.TASK_RELEASE_WCF_DESC);
		}
		return strResp;
	}
 

HTTP sends post request

There are two kinds of sending post. The reason why I divide it into two kinds is to make it convenient for everyone. The objects I want to send and json can be directly copied and used, so you don't need to turn around.

The first is to receive json directly

Parameters say:

url: url

json: Parameters


public static String doPostData(String url, String json) throws Exception {
		DefaultHttpClient client = new DefaultHttpClient();
		HttpPost post = new HttpPost(url);
		String result = "";
		HttpResponse res = null;
		try {
			StringEntity s = new StringEntity(json.toString(), "UTF-8");
			s.setContentType("application/json");
			post.setHeader("Accept", "application/json");
			post.setHeader("Content-type", "application/json; charset=utf-8");
			post.setEntity(s);
			res = client.execute(post);
			if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				result = EntityUtils.toString(res.getEntity());
				return HttpStatus.SC_OK + "";
			}
		} catch (Exception e) {
			if(res == null) {
				return "HttpResponse  For  null!";
			}
			throw new RuntimeException(e);
		}
		if(res == null || res.getStatusLine() == null) {
			return " No response ";
		}
		return res.getStatusLine().getStatusCode() + "";
	}

@Test
  public void test12() throws Exception {
    String HOST = "http://eipwcf.aspirecn.com/SvcEF/Service1.svc/WCF_EF_MSA_GetDataInfo_P";
    HttpClient client = new HttpClient();
    JSONObject json = new JSONObject();
    json.put("msgId", msgId);
    String reslut=client.doPostData(HOST, json);
  }
 

The second is that the parameter is an object

Parameter description:

url: url

tram: Object


public static String doHttpPostData(String url, TaskReleaseApprovalModel tram)
			throws Exception {
		StringBuffer sb = new StringBuffer();
		sb.append("doHttpPostData:url:" + url + ",tram:" + tram.toString() + ",contentType:" + contentType);
		logger.info(sb.toString());
		String tmpString = "";
		HttpPost request = new HttpPost(url);
		request.setHeader("Accept", "application/json");
		request.setHeader("Content-type", "application/json");
		ObjectMapper mapper = new ObjectMapper();
		String jsonString;
		try {
			jsonString = mapper.writeValueAsString(tram);
			StringEntity entity = new StringEntity(jsonString, "UTF-8");
			request.setEntity(entity);
			CloseableHttpClient client = HttpClients.createDefault();
			HttpResponse response = client.execute(request);
			if (response.getStatusLine().getStatusCode() == HttpURLConnection.HTTP_OK) {
				tmpString = EntityUtils.toString(response.getEntity());
				logger.info("the post result:tmpString:{}", tmpString);
			} else {
				logger.info("the post failure:tmpString:", tmpString);
				throw new CommonBusinessException(CommonConstants.TASK_RELEASE_WCF,
						CommonConstants.TASK_RELEASE_WCF_DESC);
			}
		} catch (Exception e) {
			logger.error(sb.toString() + ":" + e.getMessage(), e.getCause());
			throw new CommonBusinessException(CommonConstants.TASK_RELEASE_POSTWCF,
					CommonConstants.TASK_RELEASE_POSTWCF_DESC);
		}
		return tmpString;
	}

This method I don't want to write test class everyone will use, pass the past object and address can be, very convenient very simple.


Related articles: