Normally, there are many approaches to call http request in Andriod. Here I only explain following methods to call http request:
Hopefully, it helps android developer
in my opition, it should be utilize class in your project so that you can call this class everywhere. you only need to maintain one piece of source code. No necessary to reimplement your own source code again.
package rib.com.example.Util;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.InputStreamRequestEntity;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.io.IOUtils;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import rib.com.mctwo.Bean.LoginClientContext;
/**
* Http请求工具类
*
* @author Tony Peng
* @version v1.0.1
* @since 2018-12-25
*/
public class HttpRequestUtil {
private static final String AUTHORIZATION = "Authorization";
private static final String BEARER = "Bearer ";
private static final String CLIENTCONTEXT = "Client-Context";
/*
*
* Get as json request
* */
public static String getAsJson(String url, Map<String, String> headers, String param)
{
String result = "";
BufferedReader in = null;
try {
String urlNameString = url + "?" + param;
URL realUrl = new URL(urlNameString);
URLConnection connection = realUrl.openConnection();
// 设置通用的请求属性
// initialize headers
Iterator<Map.Entry<String, String>> entries = headers.entrySet().iterator();
while (entries.hasNext()) {
Map.Entry<String, String> entry = entries.next();
connection.setRequestProperty(entry.getKey(), entry.getValue());
}
// 建立实际的连接
connection.connect();
// 获取所有响应头字段
Map<String, List<String>> map = connection.getHeaderFields();
// 遍历所有的响应头字段
for (String key : map.keySet()) {
System.out.println(key + "--->" + map.get(key));
}
// 定义 BufferedReader输入流来读取URL的响应
in = new BufferedReader(new InputStreamReader(
connection.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
System.out.println("发送GET请求出现异常!" + e);
e.printStackTrace();
}
// 使用finally块来关闭输入流
finally {
try {
if (in != null) {
in.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
return result;
}
/*
* Generate Header via token and client context
* @author Tony Peng
* */
public static Map<String, String> generateHeaders(String token, Object clientContext ) {
Map<String, String> header = new HashMap<String, String>();
// add token first
if(token != null){
token = token.replaceAll("\"","");
token = token.trim();
header.put(AUTHORIZATION, BEARER + token);
}
// add client context string
if (clientContext != null) {
try {
ObjectMapper mapper = new ObjectMapper();
String jsonData = mapper.writeValueAsString(clientContext);
if (jsonData != null) {
header.put(CLIENTCONTEXT, jsonData);
}
} catch (Exception e) {
}
} else {
LoginClientContext cc = new LoginClientContext();
cc.setClientId(0);
cc.setCompanyCode("");
cc.setSignedInClientId(0);
cc.setPermissionClientId(0);
cc.setPermissionRoleId(0);
cc.setDataLanguageId(1);
cc.setCulture("en-us");
cc.setLanguage("en");
try {
ObjectMapper mapper = new ObjectMapper();
String jsonData = mapper.writeValueAsString(cc);
if (jsonData != null) {
header.put(CLIENTCONTEXT, jsonData);
}
} catch (Exception e) {
}
}
header.put("Content-Type", "application/json");
header.put("charset", "utf-8");
header.put("User-Agent","Mozilla/5.0 ( compatible ) ");
header.put("Accept", "*/*");
return header;
}
/**
* 发送post请求
*
* @param requestUrl
* 请求地址
* @param headers
* 请求头
* @param params
* 参数
* @return 返回结果
* @throws IOException
*/
public static String sendPost( String requestUrl, Map<String, String> headers, String params
) throws IOException {
byte[] requestBytes = params.getBytes("utf-8"); // 将参数转为二进制流
HttpClient httpClient = new HttpClient();// 客户端实例化
PostMethod postMethod = new PostMethod(requestUrl);
// 设置请求头
// initialize headers
Iterator<Map.Entry<String, String>> entries = headers.entrySet().iterator();
while (entries.hasNext()) {
Map.Entry<String, String> entry = entries.next();
postMethod.setRequestHeader(entry.getKey(), entry.getValue());
}
postMethod.setRequestHeader("Content-Type", "application/json");
InputStream inputStream = new ByteArrayInputStream(requestBytes, 0,
requestBytes.length);
RequestEntity requestEntity = new InputStreamRequestEntity(inputStream,
requestBytes.length, "application/json; charset=utf-8"); // 请求体
postMethod.setRequestEntity(requestEntity);
httpClient.executeMethod(postMethod);// 执行请求
InputStream soapResponseStream = postMethod.getResponseBodyAsStream();// 获取返回的流
String result = IOUtils.toString(soapResponseStream);;// 从输入流中读取数据
return result;
}
}
Normally, you had better saperete your request header. Here, I am using method "generateHeaders" to assembly your request headers. For individual developer, you just need to build your own header and sort out related URL, you can call it properly.
Note that, you had better add following packages lest that you will have complier errors (build gradle - app)
implementation 'org.apache.servicemix.bundles:org.apache.servicemix.bundles.commons-httpclient:3.1_7'
implementation 'com.fasterxml.jackson.core:jackson-databind:2.9.8'
implementation 'org.kie.modules:org-apache-commons-io-main:6.5.0.Final'