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.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Map;
import java.util.UUID;
import javax.net.ssl.HttpsURLConnection;
import static android.provider.Telephony.Mms.Part.CHARSET;
public class RequestUtil {
/**
* get请求
* @param urlStr 请求地址带参数
* @return bytes
* @throws IOException 读写异常
*/
public static byte[] getUrlBytes(String urlStr) throws IOException {
URL url = new URL(urlStr);
HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
try {
ByteArrayOutputStream out = new ByteArrayOutputStream();
InputStream in = connection.getInputStream();
if (connection.getResponseCode() != HttpsURLConnection.HTTP_OK) {
throw new IOException(connection.getResponseMessage() + ": " + urlStr);
}
int bytesRead = 0;
byte[] buffer = new byte[1024];
while ((bytesRead = in.read(buffer)) > 0) {
out.write(buffer, 0, bytesRead);
}
out.close();
return out.toByteArray();
}finally {
connection.disconnect();
}
}
/**
* get请求
* @param urlStr 请求地址带参数
* @return String
* @throws IOException 读写异常
*/
public static String getUrlString(String urlStr) throws IOException {
return new String(getUrlBytes(urlStr));
}
/**
* post请求
* @param urlStr 请求地址
* @param params 请求参数
* @return byte
* @throws IOException 读写异常
*/
public static byte[] getUrlBytesPost(String urlStr, Map<String,String> params) throws IOException {
URL url = new URL(urlStr);
StringBuffer parambuffer = new StringBuffer();
if(params != null&&!params.isEmpty()){
for(Map.Entry<String, String> entry : params.entrySet()){
parambuffer.append(entry.getKey()).append("=").
append(URLEncoder.encode(entry.getValue(),"utf-8")).
append("&");
}
}
parambuffer.deleteCharAt(parambuffer.length()-1);
Log.i("post params", parambuffer.toString());
byte[] mydata = parambuffer.toString().getBytes();
HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
try {
connection.setConnectTimeout(3000);
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setUseCaches(false);
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");//设置请求体的类型
connection.setRequestProperty("Content-Length", String.valueOf(mydata.length));
connection.connect();
OutputStream outputStream = connection.getOutputStream();
outputStream.write(mydata,0,mydata.length);
if (connection.getResponseCode() != HttpsURLConnection.HTTP_OK) {
throw new IOException(connection.getResponseMessage() + ": with " + urlStr);
}
InputStream in = connection.getInputStream();
ByteArrayOutputStream out = new ByteArrayOutputStream();
int bytesRead = 0;
byte[] buffer = new byte[1024];
while ((bytesRead = in.read(buffer)) > 0) {
out.write(buffer, 0, bytesRead);
}
out.close();
return out.toByteArray();
}finally {
connection.disconnect();
}
}
/**
* post请求
* @param urlStr 请求地址
* @param params 请求参数
* @return String
* @throws IOException 读写异常
*/
public static String getUrlStringPost(String urlStr, Map<String,String> params) throws IOException {
return new String(getUrlBytesPost(urlStr, params));
}
/**
* 文件上传
* @param file 要上传的文件
* @param fileParamName 文件参数名
* @param requestURL 请求地址
* @param params 请求参数
* @return 服务器返回的数据,失败返回null
*/
public static String uploadFile(File file,String fileParamName, String requestURL, Map<String, String> params){
String TAG = "uploadFile";
String PREFIX = "--";
String LINE_END = "\r\n";
String BOUNDARY = UUID.randomUUID().toString();
HttpsURLConnection connection = null;
try {
URL url = new URL(requestURL);
connection = (HttpsURLConnection) url.openConnection();
connection.setConnectTimeout(30 * 1000);//连接超时时间
connection.setReadTimeout(30 * 1000);//读取超时时间
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
connection.setRequestMethod("POST"); //请求方式
connection.setRequestProperty("Charset", "utf-8"); //编码
connection.setRequestProperty("connection", "keep-alive");
//connection.setRequestProperty("Cookie", "");//设置cookie,多个cookie用;分开
connection.setRequestProperty("Content-Type", "multipart/form-data" + ";boundary=" + BOUNDARY);
if(file!=null)
{
OutputStream outputSteam = connection.getOutputStream();
DataOutputStream dos = new DataOutputStream(outputSteam);
//文件以外的其他参数
if (params != null && params.size() > 0) {
for (String key : params.keySet()) {
StringBuffer sb = new StringBuffer();
String value = params.get(key);
sb.append(PREFIX).append(BOUNDARY).append(LINE_END);
sb.append("Content-Disposition: form-data; name=\"")
.append(key).append("\"").append(LINE_END)
.append(LINE_END);//name是参数名称
sb.append(value).append(LINE_END);
String param = sb.toString();
Log.i(TAG, key + "=" + param + "##");
dos.write(param.getBytes());
// dos.flush();
}
}
StringBuffer sb = new StringBuffer();
sb.append(PREFIX);
sb.append(BOUNDARY);
sb.append(LINE_END);
//文件
sb.append("Content-Disposition: form-data; name=\""+fileParamName+"\"; filename=\""+file.getName()+"\""+LINE_END);//name是参数名称;filename是带后缀文件名
sb.append("Content-Type: application/octet-stream; charset="+CHARSET+LINE_END);
sb.append(LINE_END);
dos.write(sb.toString().getBytes());
//读取文件
InputStream is = new FileInputStream(file);
byte[] bytes = new byte[1024];
int len = 0;
while((len=is.read(bytes))!=-1)
{
dos.write(bytes, 0, len);
}
is.close();
dos.write(LINE_END.getBytes());
byte[] end_data = (PREFIX+BOUNDARY+PREFIX+LINE_END).getBytes();
dos.write(end_data);
dos.flush();
//返回信息处理
int res = connection.getResponseCode();
Log.d(TAG, "response code:"+res);
if(connection.getResponseCode() == 200)
{
BufferedReader input = new BufferedReader(new InputStreamReader(connection.getInputStream()));
StringBuilder result = new StringBuilder();
String line;
while((line = input.readLine()) != null)
{
result.append(line).append("\n");
}
Log.i(TAG, result.toString());
return result.toString();//返回服务器信息
}
}
}catch (IOException e) {
Log.e(TAG, "fail to upload file",e);
}finally {
if (connection!=null) connection.disconnect();
}
return null;//上传失败返回null
}