tags: java
package com.dhtech.trumpet.common;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
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.URIBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.params.CoreProtocolPNames;
import org.apache.http.util.EntityUtils;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @author syp
* @className com.dhtech.trumpet.common.HttpClientService
* @date 2021/07/13
* @Version 1.0
* @describe:
*/
@Slf4j
public class HttpClientService {
/**
* Return successful status code
*/
private static final int SUCCESS_CODE = 200;
/**
* Send GET request
*
* @PARAM URL requests URL
* @Param NameValuePairList request parameters
* @Return JSON or string
* @throws Exception
*/
public static String sendGet(String url, List<NameValuePair> nameValuePairList) throws Exception {
CloseableHttpClient client = null;
CloseableHttpResponse response = null;
try {
client = HttpClients.createDefault();
URIBuilder uriBuilder = new URIBuilder(url);
uriBuilder.addParameters(nameValuePairList);
HttpGet httpGet = new HttpGet(uriBuilder.build());
httpGet.setHeader(new BasicHeader("Content-Type", "application/json; charset=utf-8"));
httpGet.setHeader(new BasicHeader("Accept", "application/json;charset=utf-8"));
response = client.execute(httpGet);
int statusCode = response.getStatusLine().getStatusCode();
if (SUCCESS_CODE == statusCode) {
HttpEntity entity = response.getEntity();
/**
* Get return content via Entityuitls
*/
String result = EntityUtils.toString(entity, "UTF-8");
return result;
} else {
log.error("HttpClientService-line: {}, errorMsg{}", 97, "GET request failed!");
}
} catch (Exception e) {
log.error("HttpClientService-line: {}, Exception: {}", 100, e);
} finally {
response.close();
client.close();
}
return null;
}
/**
* Send a POST request
*
* @param url
* @param file
* @return java.lang.Object
* @author xianghl
* @date 2021/7/14 9:21
*/
public static Object sendPost(String url, File file) throws Exception {
CloseableHttpClient httpClient = HttpClients.createDefault();
String result = "";
try {
String fileName = file.getName();
String base64 = file2Base64(file);
HttpPost httpPost = new HttpPost(url);
Map<String, String> map = new HashMap<>();
map.put("fileName", fileName);
map.put("fileData", base64);
StringEntity s = new StringEntity(JSON.toJSONString(map));
s.setContentEncoding("UTF-8");
// Send JSON data to set ContentType
s.setContentType("application/json");
httpPost.setEntity(s);
// Execute Submit
HttpResponse response = httpClient.execute(httpPost);
HttpEntity responseEntity = response.getEntity();
if (responseEntity != null) {
// convert the response content to a string
result = EntityUtils.toString(responseEntity, Charset.forName("UTF-8"));
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
httpClient.close();
} catch (Exception e) {
e.printStackTrace();
}
}
return result;
}
public static String file2Base64(File file) {
if (file == null) {
return null;
}
String base64 = null;
FileInputStream fin = null;
try {
fin = new FileInputStream(file);
byte[] buff = new byte[fin.available()];
fin.read(buff);
base64 = Base64.encode(buff);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fin != null) {
try {
fin.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return base64;
}
}
Involved version Some code: The key code is: Htpp.utf_8, where the character code can be used to solve the Chinese garbled code...
Post request to send Json data Modify Post request Add Headers request header Content-Type is set to application/json The encoding of the body is raw Raw is the encoding method that sends plain text w...
Reprinted at: https://blog.51cto.com/6230217/1223224...
TCP connection to send data and request definition Connect to Socket, TCP mode; disconnect Socket Download data send data Connect WiFi...
There are three ways to send http requests in java. In addition to the native connection method HttpURLConnection, there are two other ways: HTTPClient and CloseableHttpClient The following briefly in...