貌似沒什麼好說的了,直接看代碼吧!
1.get 與 post請求
package com.ax.okhttputils.okhttputils.utils;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import com.ax.okhttputils.okhttputils.inface.HttpInface;
import com.ax.okhttputils.okhttputils.inface.HttpRunInface;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* Created by TP_zhao on 2017/4/11.
*/
public class HttpUtils {
static HttpUtils httpUtils;
private static String strResult;
private static String result;
private static String results;
private static RunnUtils runnUtils;
public static HttpUtils getInstance(){
if(httpUtils==null){
httpUtils = new HttpUtils();
return httpUtils;
}
return httpUtils;
}
static HttpInface httpinfces;
/**
*
* @param URL 請求位址
* @param map 上傳的參數
* @param httpinfce 回調接口的執行個體
*/
public static void httpPost(final String URL, final Map<String, String> map, final HttpInface httpinfce){
runnUtils = new RunnUtils();
runnUtils.setInface(new HttpRunInface() {
@Override
public void carryHttp() {
getData(URL, map, httpinfce);
}
});
runnUtils.start();
}
private static void getData(String URL, Map<String, String> map, HttpInface httpinfce) {
httpinfces = httpinfce;
Set set = map.keySet();
Iterator iter = set.iterator();
final Iterator i = map.entrySet().iterator();
List<NameValuePair> params = new ArrayList<NameValuePair>(); //Post運作傳送變量必須用NameValuePair[]數組儲存
while (i.hasNext()) {
Map.Entry entry = (Map.Entry)i.next();
String key = (String) entry.getKey();
String value = (String) entry.getValue();
// Log.i("xzzxxzzx",key+" ---- "+value);
params.add(new BasicNameValuePair(key,value));
}
String uriAPI = URL; //聲明網址字元串
HttpPost httpRequest = new HttpPost(uriAPI); //建立HTTP POST聯機
HttpResponse httpResponse = null;
HttpParams httpParameters = new BasicHttpParams();
int timeoutConnection = 10000;
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
int timeoutSocket = 10000;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
httpRequest.setParams(httpParameters);
try {
httpRequest.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8)); //發出http請求
httpResponse = new DefaultHttpClient().execute(httpRequest); //取得http響應
if(httpResponse.getStatusLine().getStatusCode() == 200) {
//擷取字元串
strResult = EntityUtils.toString(httpResponse.getEntity());
handler.sendEmptyMessage(1);
try {
httpRequest.clone();
Runtime.getRuntime().gc();
} catch (CloneNotSupportedException z) {
z.printStackTrace();
}
}else{
strResult = "-1";
handler.sendEmptyMessage(6);
// Log.i("post","網絡連接配接失敗");
try {
httpRequest.clone();
Runtime.getRuntime().gc();
} catch (CloneNotSupportedException z) {
z.printStackTrace();
}
}
} catch(ConnectTimeoutException e){
// 捕獲逾時異常 并回報給調用者
e.printStackTrace();
// Toast.makeText(context,"網絡狀況不太好!",Toast.LENGTH_LONG).show();
strResult = "-1";
handler.sendEmptyMessage(6);
try {
httpRequest.clone();
Runtime.getRuntime().gc();
} catch (CloneNotSupportedException z) {
z.printStackTrace();
}
try {
httpRequest.clone();
Runtime.getRuntime().gc();
} catch (CloneNotSupportedException z) {
z.printStackTrace();
}
// Log.i("post","網絡連接配接失敗");
}catch (IOException e) {
try {
httpRequest.clone();
Runtime.getRuntime().gc();
} catch (CloneNotSupportedException z) {
z.printStackTrace();
strResult = "-1";
}
e.printStackTrace();
strResult = "-1";
handler.sendEmptyMessage(6);
// Log.i("post","網絡連接配接失敗");
try {
httpRequest.clone();
Runtime.getRuntime().gc();
} catch (CloneNotSupportedException z) {
z.printStackTrace();
}
}
}
static Handler handler =new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what){
case 1:
httpinfces.setResData(strResult);
// runnUtils.interrupt();
runnUtils = null;
Runtime.getRuntime().gc();
break;
case 2:
httpInface.setResData(result);
break;
case 3:
httpInface.shibai(result);
break;
case 6:
httpinfces.shibai(strResult);
break;
}
}
};
/**
* url 你請求的接口
* httpInfaces 回調對象
*/
static HttpInface httpInface;
public static void httpGET(String url, HttpInface httpInfaces){
httpInface = httpInfaces;
final String serverURL =url;
new Thread(new Runnable() {
@Override
public void run() {
HttpGet httpRequest = new HttpGet(serverURL);// 建立http get聯機
HttpResponse httpResponse = null;// 發出http請求
try {
HttpParams httpParameters = new BasicHttpParams();
int timeoutConnection = 60000;
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
int timeoutSocket = 60000;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
httpResponse = httpClient.execute(httpRequest);
if (httpResponse.getStatusLine().getStatusCode() == 200) {
// 擷取相應的字元串
result = EntityUtils.toString(httpResponse.getEntity());
handler.sendEmptyMessage(2);
try {
httpRequest.clone();
httpClient = null;
Runtime.getRuntime().gc();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
}else{
result = "網絡請求失敗";
handler.sendEmptyMessage(3);
Log.i("zxxzxz",result+"1");
}
} catch(ConnectTimeoutException e){
// 捕獲逾時異常 并回報給調用者
e.printStackTrace();
// Toast.makeText(context,"網絡狀況不太好!",Toast.LENGTH_LONG).show();
result = "網絡請求失敗";
handler.sendEmptyMessage(3);
Log.i("zxxzxz",result+"2");
}catch (IOException e) {
e.printStackTrace();
result = "網絡請求失敗";
handler.sendEmptyMessage(3);
Log.i("zxxzxz",result+"3");
}
}
}).start();
}
}
2.圖檔上傳
2.1基于okhttp上傳
package com.ax.okhttputils.okhttputils.utils;
import android.os.Handler;
import android.os.Message;
import com.ax.okhttputils.okhttputils.inface.HttpInface;
import java.io.File;
import java.io.IOException;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
/**
* Created by HIAPAD on 2018/2/7.
* function 上傳圖檔
*author 趙先森
*
*/
public class UploadImageUtils {
private static final MediaType MEDIA_TYPE_PNG = MediaType.parse("image/png");
static HttpInface httpInfaces;
private static String results;
/**
*
* @param url 請求位址
* @param file 上傳圖檔存放的路徑
* @param key 圖檔對應的key
* @param httpInface 回調執行個體
*/
public static void uploadImg(String url, File file, String key, HttpInface httpInface) {
httpInfaces = httpInface;
final OkHttpClient client = new OkHttpClient();
// mImgUrls為存放圖檔的url集合
MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM);
if (file!=null) {
builder.addFormDataPart(key, file.getName(), RequestBody.create(MEDIA_TYPE_PNG, file));
}
MultipartBody requestBody = builder.build();
//建構請求
final Request request = new Request.Builder()
.url(url)//位址
.post(requestBody)//添加請求體
.build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
results = "失敗";
handlers.sendEmptyMessage(1);
// System.out.println("上傳失敗:e.getLocalizedMessage() = " + e.getLocalizedMessage());
}
@Override
public void onResponse(Call call, Response response) throws IOException {
results = response.body().string();
handlers.sendEmptyMessage(1);
// System.out.println("上傳照片成功:response = " + response.body().string());
}
});
}
static Handler handlers = new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what){
case 1:
httpInfaces.setResData(results);
break;
}
}
};
}
2.2 from表單上傳
package com.ax.okhttputils.okhttputils.utils;
import android.os.Environment;
import android.util.Log;
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.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.util.Iterator;
import java.util.Map;
import java.util.UUID;
public class HttpRequester {
private static final int TIME_OUT = 10*1000;
private static final String BOUNDARY = "-------45962402127348";
private static final String FILE_ENCTYPE = "multipart/form-data";
private static final String CHARSET = "utf-8";
static String key;
public static InputStream post(String urlStr, Map<String, String> params,
Map<String, File> images) {
InputStream is = null;
try {
URL url = new URL(urlStr);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setConnectTimeout(5000);
con.setDoInput(true);
con.setDoOutput(true);
con.setUseCaches(false);
con.setRequestMethod("POST");
con.setRequestProperty("Connection", "Keep-Alive");
con.setRequestProperty("Charset", "UTF-8");
con.setRequestProperty("Content-Type", FILE_ENCTYPE + "; boundary="
+ BOUNDARY);
StringBuilder sb = null;
DataOutputStream dos = new DataOutputStream(con.getOutputStream());;
if (params != null) {
sb = new StringBuilder();
for (String s : params.keySet()) {
sb.append("--");
sb.append(BOUNDARY);
sb.append("\r\n");
sb.append("Content-Disposition: form-data; name=\""+key+"\"");
sb.append(s);
sb.append("\"\r\n\r\n");
sb.append(params.get(s));
sb.append("\r\n");
}
dos.write(sb.toString().getBytes());
}
if (images != null) {
for (String s : images.keySet()) {
File f = images.get(s);
sb = new StringBuilder();
sb.append("--");
sb.append(BOUNDARY);
sb.append("\r\n");
sb.append("Content-Disposition: form-data; name=\"");
sb.append(s);
sb.append("\"; filename=\"");
sb.append(f.getName());
sb.append("\"\r\n");
sb.append("Content-Type: image/jpeg");//這裡注意!如果上傳的不是圖檔,要在這裡改檔案格式,比如txt檔案,這裡應該是text/plain
sb.append("\r\n\r\n");
dos.write(sb.toString().getBytes());
FileInputStream fis = new FileInputStream(f);
byte[] buffer = new byte[1024];
int len;
while ((len = fis.read(buffer)) != -1) {
dos.write(buffer, 0, len);
}
dos.write("\r\n".getBytes());
fis.close();
}
sb = new StringBuilder();
sb.append("--");
sb.append(BOUNDARY);
sb.append("--\r\n");
dos.write(sb.toString().getBytes());
}
dos.flush();
if (con.getResponseCode() == 200)
is = con.getInputStream();
dos.close();
// con.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return is;
}
public static byte[] read(InputStream inStream) throws Exception{
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
while( (len = inStream.read(buffer)) != -1){
outputStream.write(buffer, 0, len);
}
inStream.close();
return outputStream.toByteArray();
}
public void ysing(File file){
String sdStatus = Environment.getExternalStorageState();
}
/**
*
* @param file 圖檔存放路徑
* @param RequestURL 上傳位址
* @param param 參數
* @param keyzz 圖檔對應的key
* @return
*/
public static String uploadFile(File file, String RequestURL, Map<String, String> param,String keyzz){
key = keyzz;
String result = null;
String BOUNDARY = UUID.randomUUID().toString(); //邊界辨別 随機生成
String PREFIX = "--" , LINE_END = "\r\n";
String CONTENT_TYPE = "multipart/form-data"; //内容類型
//壓縮圖檔
// 顯示進度框
// showProgressDialog();
try {
URL url = new URL(RequestURL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(TIME_OUT);
conn.setConnectTimeout(TIME_OUT);
conn.setDoInput(true); //允許輸入流
conn.setDoOutput(true); //允許輸出流
conn.setUseCaches(false); //不允許使用緩存
conn.setRequestMethod("POST"); //請求方式
conn.setRequestProperty("Charset", CHARSET); //設定編碼
conn.setRequestProperty("connection", "keep-alive");
conn.setRequestProperty("Content-Type", CONTENT_TYPE + ";boundary=" + BOUNDARY);
if(file!=null){
/**
* 當檔案不為空,把檔案包裝并且上傳
*/
DataOutputStream dos = new DataOutputStream( conn.getOutputStream());
StringBuffer sb = new StringBuffer();
String params = "";
if (param != null && param.size() > 0) {
Iterator<String> it = param.keySet().iterator();
while (it.hasNext()) {
sb = null;
sb = new StringBuffer();
String keys = it.next();
String value = param.get(keys);
Log.i("zzzz",keys+"...."+value);
sb.append(PREFIX).append(BOUNDARY).append(LINE_END);
sb.append("Content-Disposition: form-data; name=\"").append(keys).append("\"").append(LINE_END).append(LINE_END);
sb.append(value).append(LINE_END);
params = sb.toString();
dos.write(params.getBytes());
// dos.flush();
}
}
sb = new StringBuffer();
sb.append(PREFIX);
sb.append(BOUNDARY);
sb.append(LINE_END);
/**
* 這裡重點注意:
* name裡面的值為伺服器端需要key 隻有這個key 才可以得到對應的檔案
* filename是檔案的名字,包含字尾名的 比如:abc.png
*/
sb.append("Content-Disposition: form-data; name=\""+keyzz+"\";filename=\""+file.getName()+"\""+LINE_END);
sb.append("Content-Type: image/pjpeg; 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();
/**
* 擷取響應碼 200=成功
* 當響應成功,擷取響應的流
*/
int res = conn.getResponseCode();
System.out.println("res========="+res);
if(res==200){
InputStream input = conn.getInputStream();
StringBuffer sb1= new StringBuffer();
int ss ;
while((ss=input.read())!=-1){
sb1.append((char)ss);
}
result = sb1.toString();
Log.i("pppp",result);
// // 移除進度框
// removeProgressDialog();
}
else{
}
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
}
好了,就這樣吧,有demo,大家可以點選下載下傳!感覺該标注的都已經在代碼的注釋裡說了,至于實作原理什麼,大家又不懂的,咱們可以共同探讨!
下載下傳位址:http://download.csdn.net/download/qq_34148178/10245456