import android.graphics.Bitmap;
import android.util.Log;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Map;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
/**
* Created by my on 2018/4/27.
*/
public class HttpUrls {
public static String mtoken;
public static String ssid;
//正常POST提交数据
public static StringBuffer post(String urlString, StringBuffer param) {
Log.e("dbHttpUrls",urlString);
if(param!=null)
Log.e("dbHttpUrls_data",param.toString());
// ACache ac=ACache.get(MyApplication.getContext());
// mtoken=ac.getAsString("token");
StringBuffer sb = new StringBuffer();
URL url = null;
HttpURLConnection connection = null;
DataOutputStream out = null;
BufferedReader in = null;
try {
url = new URL(urlString);
//关键代码
//ignore https certificate validation |忽略 https 证书验证
if (url.getProtocol().toUpperCase().equals("HTTPS")) {
Log.e("SmartHttpUrls","connect");
trustAllHosts();
HttpsURLConnection https = (HttpsURLConnection) url
.openConnection();
https.setHostnameVerifier( new HostnameVerifier() {
@Override
public boolean verify(String s, SSLSession sslSession) {
return true;//通过所有主机名称
}
});
connection = https;
} else {
connection = (HttpURLConnection) url.openConnection();
}
if (ssid != null) {
connection.setRequestProperty("Cookie", ssid);
}
connection.setReadTimeout(60000);
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setUseCaches(false);
connection.setInstanceFollowRedirects(true);
connection.setRequestProperty("Content-Type",
"application/json");
if (mtoken!=null){
System.out.println("发送附带token"+mtoken);
connection.setRequestProperty("Authorization",mtoken);
}
// connection.setRequestProperty("User-agent","SmartApp");
// connection.setRequestProperty("Referer", "https://app.psmartcloud.com/");
// if(mtoken!=null){
// connection.setRequestProperty("xtoke",mtoken);}
// if (urlString.equals(Urls.BASE_URL+Urls.UsrLogin)) {
// //set cookie
// String cookieVal = connection.getHeaderField("Set-Cookie");
// if (cookieVal != null) {
// String[] cookieArray = cookieVal.split(";");
// cookieVal = cookieArray[0];
// if (cookieVal != null) {
// ssid=cookieVal;
//
// }
// }
// }
// connection.connect();
if (param != null) {
out = new DataOutputStream(
connection.getOutputStream());
out.write(param.toString().getBytes());//out.writeBytes(param);
out.flush();
}
int code= connection.getResponseCode();
if (code==200) {
in = new BufferedReader(new InputStreamReader(
connection.getInputStream()), 512);
String line;
while ((line = in.readLine()) != null) {
sb.append(line.trim());
}
}else {
Log.e("db_Https", String.valueOf(code));
}
// Log.e("db_testpost",sb.toString());
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}finally{
if (out != null) {
try {
out.close();
} catch (IOException e) {
}
}
if (in != null) {
try {
in.close();
} catch (IOException e) {
}
}
if (connection != null) {
connection.disconnect();
}
}
return sb;
}
//使用表单提交数据
public static String submitPostData(String strUrlPath, Map<String, String> params, String encode) {
byte[] data = getRequestData(params, "utf-8").toString().getBytes();//获得请求体 utf-8 是encode位置
try {
//String urlPath = "http://192.168.1.9:80/JJKSms/RecSms.php";
URL url = new URL(strUrlPath);
HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
httpURLConnection.setConnectTimeout(60000); //设置连接超时时间
httpURLConnection.setDoInput(true); //打开输入流,以便从服务器获取数据
httpURLConnection.setDoOutput(true); //打开输出流,以便向服务器提交数据
httpURLConnection.setRequestMethod("POST"); //设置以Post方式提交数据
httpURLConnection.setUseCaches(false); //使用Post方式不能使用缓存
//设置请求体的类型是文本类型
httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
//设置请求体的长度
httpURLConnection.setRequestProperty("Content-Length", String.valueOf(data.length));
//获得输出流,向服务器写入数据
OutputStream outputStream = httpURLConnection.getOutputStream();
outputStream.write(data);
int response = httpURLConnection.getResponseCode(); //获得服务器的响应码
if(response == HttpURLConnection.HTTP_OK) {
System.out.println("服务器相应成功200");
InputStream inptStream = httpURLConnection.getInputStream();
return dealResponseResult(inptStream); //处理服务器的响应结果
}
} catch (IOException e) {
//e.printStackTrace();
return "err: " + e.getMessage().toString();
}
return "-1";
}
public static void trustAllHosts() {
// Create a trust manager that does not validate certificate chains
// Android use X509 cert
TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[] {};
}
public void checkClientTrusted(X509Certificate[] chain,
String authType) throws CertificateException {
}
public void checkServerTrusted(X509Certificate[] chain,
String authType) throws CertificateException {
}
} };
// Install the all-trusting trust manager
try {
SSLContext sc = SSLContext.getInstance("TLS");
sc.init(null, trustAllCerts, new java.security.SecureRandom());
HttpsURLConnection
.setDefaultSSLSocketFactory(sc.getSocketFactory());
} catch (Exception e) {
e.printStackTrace();
}
}
public final static HostnameVerifier DO_NOT_VERIFY = new HostnameVerifier() {
public boolean verify(String hostname, SSLSession session) {
return true;
}
};
//文件路径转换
public static byte[] File2byte(String filePath)
{
byte[] buffer = null;
try
{
File file = new File(filePath);
FileInputStream fis = new FileInputStream(file);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] b = new byte[1024];
int n;
while ((n = fis.read(b)) != -1)
{
bos.write(b, 0, n);
}
fis.close();
bos.close();
buffer = bos.toByteArray();
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
return buffer;
}
//Bitmap转换byte
public static byte[] getbyte(Bitmap bitmap){
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] datas = baos.toByteArray();
return datas;
}
public static String Get(String str) throws IOException {
URL url1 = new URL(str);
URLConnection rulConnection = url1.openConnection();
HttpURLConnection conn = (HttpURLConnection) rulConnection;
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setConnectTimeout(10000);
conn.setRequestMethod("GET");
conn.connect();
if (conn.getResponseCode() == 200) {
Log.e("httpconnect", "链接正常开始解析");
} else {
Log.e("服务器链接失败", "1");
return "404";
}
InputStream is = conn.getInputStream();
// Intent intent = new Intent(MyActivity.BASEBRCSHOW);
// intent.putExtra("Toast.showbrc", "服务器链接失败错误代码" + Responsecode);
// context.sendBroadcast(intent);
BufferedReader reader = new BufferedReader(
new InputStreamReader(is));
String line = null;
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null) {
sb.append(line);//+"/n"
}
is.close();
return sb.toString();
}
/*
* Function : 封装请求体信息
* Param : params请求体内容,encode编码格式
*/
public static StringBuffer getRequestData(Map<String, String> params, String encode) {
StringBuffer stringBuffer = new StringBuffer(); //存储封装好的请求体信息
try {
for(Map.Entry<String, String> entry : params.entrySet()) {
stringBuffer.append(entry.getKey())
.append("=")
.append(URLEncoder.encode(entry.getValue(), encode))
.append("&");
}
stringBuffer.deleteCharAt(stringBuffer.length() - 1); //删除最后的一个"&"
} catch (Exception e) {
e.printStackTrace();
}
return stringBuffer;
}
/*
* Function : 处理服务器的响应结果(将输入流转化成字符串)
* Param : inputStream服务器的响应输入流
*/
public static String dealResponseResult(InputStream inputStream) {
String resultData = null; //存储处理结果
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
byte[] data = new byte[1024];
int len = 0;
try {
while((len = inputStream.read(data)) != -1) {
byteArrayOutputStream.write(data, 0, len);
}
} catch (IOException e) {
e.printStackTrace();
}
resultData = new String(byteArrayOutputStream.toByteArray());
return resultData;
}
}
httpURL工具类
最新推荐文章于 2024-04-29 20:35:32 发布