Get请求
示例代码
findViewById(R.id.sendGetReq).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
LogUtil.e("发送Get请求");
String result = null;
String argUrl = "请求url";
Map<String, String> mapData = new HashMap<>();
mapData.put("张三", "23");
mapData.put("李四", "24");
mapData.put("王五", "25");
try {
result = HttpUtils.getWithParams(argUrl, mapData, null);
} catch (IOException e) {
e.printStackTrace();
}
JSONObject resultJson = JSONObject.parseObject(result);
String resultKey = resultJson.getString("需要校验的返回值");
if (!resultKey.equals("1")) {
LogUtil.e("请求失败...");
return;
}
LogUtil.e("请求成功!");
return;
}
});
HttpUtils
package com.gaojc.text.Utils;
import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.Proxy;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
public class HttpUtils {
public static String getWithParams(String argUrl, Map<String, String> headers, Map<String, String> params, Proxy proxy) throws IOException {
String requestUrl = getRequestUrl(argUrl, params);
return get(requestUrl, headers, proxy);
}
public static String getRequestUrl(String url, Map<String, String> params) {
try {
StringBuilder sb = new StringBuilder();
sb.append(url);
if (url.indexOf("&") > 0 || url.indexOf("?") > 0) {
sb.append("&");
} else {
sb.append("?");
}
for (Map.Entry<String, String> urlParams : params.entrySet()) {
String value = urlParams.getValue();
String urlValue = null;
if (value != null) {
urlValue = URLEncoder.encode(value, "UTF-8");
}
sb.append(urlParams.getKey()).append("=").append(urlValue).append("&");
}
sb.deleteCharAt(sb.length() - 1);
return sb.toString();
} catch (Exception e) {
e.printStackTrace();
}
return url;
}
public static String get(String argUrl, Map<String, String> headers, Proxy proxy) throws IOException {
LogUtil.e("请求的url是:" + argUrl);
InputStream is = null;
ByteArrayOutputStream os = null;
HttpURLConnection urlConnection = null;
try {
URL url = new URL(argUrl);
if (proxy == null){
urlConnection = (HttpURLConnection) url.openConnection();
}else {
urlConnection = (HttpURLConnection) url.openConnection(proxy);
}
urlConnection.setRequestMethod("GET");
urlConnection.setConnectTimeout(20000);
urlConnection.setReadTimeout(20000);
urlConnection.setDoInput(true);
urlConnection.setUseCaches(false);
if (headers != null){
for (Map.Entry<String, String> entry : headers.entrySet()) {
urlConnection.setRequestProperty(entry.getKey(),entry.getValue());
}
}
urlConnection.connect();
int responseCode = urlConnection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK){
is = urlConnection.getInputStream();
os = new ByteArrayOutputStream();
byte[] tmp = new byte[1024];
int i = is.read(tmp);
while (i > 0){
os.write(tmp,0,i);
i = is.read(tmp);
}
byte[] bs = os.toByteArray();
return new String(bs);
}
throw new IOException("responseCode:" + responseCode);
} catch (Exception e) {
throw e;
}finally {
if (is != null){
is.close();
}
if (os != null){
os.close();
}
if (urlConnection != null){
urlConnection.disconnect();
}
}
}
}
Post请求
示例代码
findViewById(R.id.sendPostReq).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
LogUtil.e("发送Post请求...");
String result = null;
String argUrl = "请求url";
JSONObject jsonObject = new JSONObject();
jsonObject.put("张三", "23");
jsonObject.put("李四", "24");
jsonObject.put("王五", "25");
String param = jsonObject.toJSONString();
try {
result = HttpUtils.postWithJson(argUrl, null, param, null);
} catch (IOException e) {
e.printStackTrace();
}
JSONObject resultJsonObject = null;
resultJsonObject = JSONObject.parseObject(result);
String value = resultJsonObject.getString("key");
if (!value.equals("1")) {
LogUtil.e("请求失败");
return;
}
LogUtil.e("请求成功");
return;
}
});
HttpUtils
package com.gaojc.text.Utils;
import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.Proxy;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
public class HttpUtils {
public static String postWithJson(String argUrl, Map<String, String> headers, String jsonStr, Proxy proxy) throws IOException {
if (headers == null) {
headers = new HashMap<>();
}
headers.put("Content-Type", "application/json");
headers.put("Charset", "UTF-8");
headers.put("Connection", "Close");
return post(argUrl, headers, jsonStr, proxy);
}
public static String post(String argUrl, Map<String, String> headers, String postData, Proxy proxy) throws IOException {
InputStream is = null;
BufferedWriter writer = null;
ByteArrayOutputStream os = null;
HttpURLConnection connection = null;
try {
URL url = new URL(argUrl);
if (proxy == null) {
connection = (HttpURLConnection) url.openConnection();
} else {
connection = (HttpURLConnection) url.openConnection(proxy);
}
connection.setRequestMethod("POST");
connection.setConnectTimeout(20000);
connection.setReadTimeout(20000);
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setUseCaches(false);
if (headers != null) {
for (Map.Entry<String, String> entry : headers.entrySet()) {
connection.setRequestProperty(entry.getKey(), entry.getValue());
}
}
connection.connect();
if (postData != null) {
writer = new BufferedWriter(new OutputStreamWriter(connection.getOutputStream(), "UTF-8"));
writer.write(postData);
writer.close();
}
int responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
is = connection.getInputStream();
os = new ByteArrayOutputStream();
byte[] tmp = new byte[1024];
int i = is.read(tmp);
while (i > 0) {
os.write(tmp, 0, i);
i = is.read(tmp);
}
byte[] bs = os.toByteArray();
return new String(bs);
}
throw new IOException("responseCode:" + responseCode);
} catch (Exception e) {
throw e;
} finally {
if (is != null)
is.close();
if (writer != null)
writer.close();
if (os != null)
os.close();
if (connection != null)
connection.disconnect();
}
}
}