編輯:關於Android編程
這篇博客是來了解下,頭像上傳如何實現,我們httpurlconnection和Volley來實現
首先了解下布局文件
我們先看httpurl如何實現頭像上傳的?
頭像上傳其實本質上就是將某個需要上傳的圖片轉為byte[]數組,然後在通過Base64.encodeToString轉為字符串
首先添加頭部體部分,用來生成json字符串,這裡說一下,我們公司是直接拼接的方式,當然你也可以用fastson、Gson、JsonObject來生成json格式
/** * 生成數據上傳的頭部,需要數據國鼎id,應用類型,操作系統類型 */ private void addUserInfosHead() { headParameters.clear(); headParameters.add("godin_id", "0e6ad2a71e31752deb69d6e8c9eabe76"); headParameters.add("app_type", "3"); headParameters.add("os_type", "android"); } /** * 生成數據上傳的數據包體 */ private void addRequestBodyInfos() { bodyParameters.clear(); bodyParameters.add("photo_type", "jpeg"); bodyParameters.add("context", Base64.encodeToString(bitmap2Bytes, Base64.DEFAULT)); bodyParameters.add("nickname", nick_name.getText().toString()); }
樓上的Base64.encodeToString(bitmap2Bytes, Base64.DEFAULT)就是將圖片的二進制文件轉為字符串
我們公司的封裝代碼中,以下代碼就是生成json格式
requestion = ProtocolUtil.buildJSONPacketBody(headParameters, bodyParameters);
看看Json格式把:
然後就是點擊上傳即可,我用的網絡請求是https的,所以在initHttps中進行一些證書的認證之類的,然後就打開網絡鏈接conn,然後就獲取相應碼即可
initHttps(); URL url = new URL(urlString); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setConnectTimeout(5000); conn.setDoOutput(true);//設置允許輸出 conn.setRequestMethod("POST"); conn.setRequestProperty("User-Agent", "Fiddler"); conn.setRequestProperty("Content-Type", "application/json"); conn.setRequestProperty("Charset", "utf-8"); OutputStream os = conn.getOutputStream(); os.write(content.getBytes()); os.close(); /*服務器返回的響應碼*/ int code = conn.getResponseCode(); if (code == 200) { Log.d("Evelyn", "response code:" + code); } conn.disconnect();
最後看返回結果即可
我們再看看Volley如何實現頭像上傳的?
之前的幾篇博客中,有對volley、Gson的封裝使用,本篇博客就簡單使用即可
StringRequest request = new StringRequest(Method.POST, url, new Listener() { @Override public void onResponse(String arg0) { Log.e("TAG", "volley onResponse--->>" + arg0); /** * {"Response":{"head":{"statuscode":"000000", * "statusmsg":"sucess"}}} */ } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError arg0) { } }) { @Override public byte[] getBody() throws AuthFailureError { return requestStringBytes; } @Override public String getBodyContentType() { return String.format( "application/x-www-form-urlencoded; charset=%s", "utf-8"); } @Override public Map getHeaders() throws AuthFailureError { Map headers = new HashMap (); headers.put("Charset", "UTF-8"); headers.put("Content-Type", "application/x-javascript"); headers.put("Accept-Encoding", "gzip,deflate"); return headers; } }; // 設置標簽 queue.add(request); queue.start();
代碼也很簡單;
getBodyContentType這裡是設置請求的東東的格式化
getHeaders這裡也是設置一些需要的參數(我當時也是搜的百度,麼有這些設置,無法相應正確返回值)
@Override public byte[] getBody() throws AuthFailureError { return requestStringBytes; }
這個就是需要的body[] 我們就用httpurlconnect中的那個json字符串即可
requestStringBytes = requestion.getBytes("UTF-8");
然後一樣接受返回值即可,如下截圖是本公司返回的json格式
////////////////////////////////以下是代碼區//////////////////////////////////////////////////////////////
activity_main.xml
MainActivity這個類中我將url屏蔽了,因為是公司上線項目,不方便,呵呵
package com.example.uploadphoto2server; import java.io.ByteArrayOutputStream; import java.io.UnsupportedEncodingException; import java.util.HashMap; import java.util.Map; import android.app.Activity; import android.content.res.Resources; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.Bundle; import android.util.Base64; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; import com.android.volley.AuthFailureError; import com.android.volley.Request.Method; import com.android.volley.RequestQueue; import com.android.volley.Response; import com.android.volley.Response.Listener; import com.android.volley.VolleyError; import com.android.volley.toolbox.StringRequest; import com.android.volley.toolbox.Volley; import com.google.gson.Gson; public class MainActivity extends Activity implements OnClickListener { TextView nick_name; ImageView image; Button upload, uploadByvolley; private JsonParameters headParameters; private JsonParameters bodyParameters; private DataToServer userInfosToServer; private byte[] bitmap2Bytes; public RequestQueue queue; private String requestion; private byte[] requestStringBytes; String url = "https://10.0.5.48:7771/xxxxxx"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //volley隊列 queue = Volley.newRequestQueue(this); //昵稱 nick_name = (TextView) findViewById(R.id.nick_name); //頭像 image = (ImageView) findViewById(R.id.image); //httpurlconnection上傳頭像、昵稱 upload = (Button) findViewById(R.id.upload); //volley上傳頭像、昵稱 uploadByvolley = (Button) findViewById(R.id.uploadByvolley); upload.setOnClickListener(this); uploadByvolley.setOnClickListener(this); //用來封裝 請求頭體 headParameters = new JsonParameters(); bodyParameters = new JsonParameters(); /** * 獲取頭像的二進制碼文件 */ Resources res = getResources(); Bitmap bmp = BitmapFactory.decodeResource(res, R.drawable.ic_launcher); bitmap2Bytes = Bitmap2Bytes(bmp); /* * 添加請求頭,請求體----這是公司的方式 */ addUserInfosHead(); addRequestBodyInfos(); /** * 生成json格式的字符串 */ requestion = ProtocolUtil.buildJSONPacketBody(headParameters, bodyParameters); Log.i("Evelyn", "requestion-->>"+requestion); /** * volley需要的body[] */ requestStringBytes = null; try { requestStringBytes = requestion.getBytes("UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } public byte[] Bitmap2Bytes(Bitmap bm) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); bm.compress(Bitmap.CompressFormat.PNG, 100, baos); return baos.toByteArray(); } @Override public void onClick(View v) { // upload image to server if (v.getId() == R.id.uploadByvolley) { StringRequest request = new StringRequest(Method.POST, url, new Listener() { @Override public void onResponse(String arg0) { Log.e("TAG", "volley onResponse--->>" + arg0); /** * {"Response":{"head":{"statuscode":"000000", * "statusmsg":"sucess"}}} */ } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError arg0) { } }) { @Override public byte[] getBody() throws AuthFailureError { return requestStringBytes; } @Override public String getBodyContentType() { return String.format( "application/x-www-form-urlencoded; charset=%s", "utf-8"); } @Override public Map getHeaders() throws AuthFailureError { Map headers = new HashMap (); headers.put("Charset", "UTF-8"); headers.put("Content-Type", "application/x-javascript"); headers.put("Accept-Encoding", "gzip,deflate"); return headers; } }; // 設置標簽 queue.add(request); queue.start(); } if (v.getId() == R.id.upload) { // 上傳用戶信息到後端服務器 userInfosToServer = new DataToServer(requestion, url); new Thread() { @Override public void run() { userInfosToServer.uploadFile(); } }.start(); } } /** * 生成數據上傳的頭部,需要數據國鼎id,應用類型,操作系統類型 */ private void addUserInfosHead() { headParameters.clear(); headParameters.add("godin_id", "0e6ad2a71e31752deb69d6e8c9eabe76"); headParameters.add("app_type", "3"); headParameters.add("os_type", "android"); } /** * 生成數據上傳的數據包體 */ private void addRequestBodyInfos() { bodyParameters.clear(); bodyParameters.add("photo_type", "jpeg"); bodyParameters.add("context", Base64.encodeToString(bitmap2Bytes, Base64.DEFAULT)); bodyParameters.add("nickname", nick_name.getText().toString()); } }
DataToServer
package com.example.uploadphoto2server; import java.io.IOException; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.Socket; import java.net.URL; import java.net.UnknownHostException; import java.security.KeyManagementException; import java.security.KeyStore; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.security.UnrecoverableKeyException; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLContext; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; import org.apache.http.conn.ssl.SSLSocketFactory; import android.util.Log; /** * Created by Evelyn on 2016/7/5. */ public class DataToServer { //private String urlString = "https://www.imlianxi.com:7771/ExceptionLog"; private String urlString; private String content = null; public DataToServer(String requestJson, String path) { this.content = requestJson; this.urlString = path; } /* 上傳文件至Server的方法 */ public void uploadFile() { try { initHttps(); URL url = new URL(urlString); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setConnectTimeout(5000); conn.setDoOutput(true);//設置允許輸出 conn.setRequestMethod("POST"); conn.setRequestProperty("User-Agent", "Fiddler"); conn.setRequestProperty("Content-Type", "application/json"); conn.setRequestProperty("Charset", "utf-8"); OutputStream os = conn.getOutputStream(); os.write(content.getBytes()); os.close(); /*服務器返回的響應碼*/ int code = conn.getResponseCode(); if (code == 200) { Log.d("Evelyn", "response code:" + code); } conn.disconnect(); } catch (Exception e) { e.printStackTrace(); } } private void initHttps() { try { KeyStore trustStore = KeyStore.getInstance(KeyStore .getDefaultType()); trustStore.load(null, null); SSLSocketFactoryEx sf = new SSLSocketFactoryEx(trustStore); HttpsURLConnection.setDefaultSSLSocketFactory(sf.getSSLContext() .getSocketFactory()); HttpsURLConnection .setDefaultHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); } catch (Exception e) { } } static class SSLSocketFactoryEx extends SSLSocketFactory { SSLContext sslContext = SSLContext.getInstance("TLS"); public SSLSocketFactoryEx(KeyStore truststore) throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException { super(truststore); TrustManager tm = new X509TrustManager() { public java.security.cert.X509Certificate[] getAcceptedIssuers() { return null; } @Override public void checkClientTrusted( java.security.cert.X509Certificate[] chain, String authType) throws java.security.cert.CertificateException { } @Override public void checkServerTrusted( java.security.cert.X509Certificate[] chain, String authType) throws java.security.cert.CertificateException { } }; sslContext.init(null, new TrustManager[] { tm }, null); } @Override public Socket createSocket(Socket socket, String host, int port, boolean autoClose) throws IOException, UnknownHostException { return sslContext.getSocketFactory().createSocket(socket, host, port, autoClose); } @Override public Socket createSocket() throws IOException { return sslContext.getSocketFactory().createSocket(); } public SSLContext getSSLContext() { return sslContext; } } }
ProtocolUtil
package com.example.uploadphoto2server; import android.annotation.SuppressLint; import android.content.Context; import android.net.ConnectivityManager; import android.net.NetworkInfo; /** * simple tools to handle protocol for apps. */ public class ProtocolUtil { public static final String COLON = ": "; public static final String LEFT_ANGLE_BRACKET = "{"; public static final String RIGHT_ANGLE_BRACKET = "}"; public static String buildJSONPacketBody(String[] headKey, Object[] headValue, String[] bodyKey, Object[] bodyValue) { if (((headKey == null || headKey.length == 0) && (headValue == null || headValue.length == 0) && (bodyKey == null || bodyKey.length == 0) && (bodyValue == null || bodyValue.length == 0))) { throw new IllegalArgumentException(); } StringBuffer sb = new StringBuffer(LEFT_ANGLE_BRACKET + "\r\n"); sb.append("\t\"Request\"" + COLON + LEFT_ANGLE_BRACKET + "\r\n"); if (headKey != null) { sb.append("\t\t\"head\"" + COLON + LEFT_ANGLE_BRACKET + "\r\n"); for (int i = 0; i < headKey.length; i++) { sb.append("\t\t\t\"" + headKey[i].toLowerCase() + "\"" + COLON) .append(JSONUtil.object2json(headValue[i])); if(i != headKey.length -1) { sb.append(","); } sb.append("\r\n"); } sb.append("\t\t" + RIGHT_ANGLE_BRACKET+ ",\r\n"); } if (bodyKey != null) { sb.append("\t\t\"body\"" + COLON + LEFT_ANGLE_BRACKET + "\r\n"); for (int i = 0; i < bodyKey.length; i++) { if (bodyKey[i] == null || bodyKey[i].equals("")) { continue; } sb.append("\t\t\t\"" + bodyKey[i].toLowerCase() + "\"" + COLON) .append(JSONUtil.object2json(bodyValue[i])); if(i != bodyKey.length -1) { sb.append(","); } sb.append("\r\n"); } sb.append("\t\t" + RIGHT_ANGLE_BRACKET+ "\r\n"); } sb.append("\t" + RIGHT_ANGLE_BRACKET + "\r\n"); sb.append(RIGHT_ANGLE_BRACKET); clearObjectArray(headKey, headValue, bodyKey, bodyValue); return sb.toString(); } private static void clearObjectArray(String[] hk, Object[] hv, String[] bk, Object[] bv) { if (hk != null && hv != null) { for (int i = 0; i < hk.length; i++) { hk[i] = null; hv[i] = null; } } hk = null; hv = null; if (bk != null && bv != null) { for (int i = 0; i < bk.length; i++) { bk[i] = null; bv[i] = null; } } bk = null; bv = null; } public static String buildJSONPacketBody(JsonParameters headValues, JsonParameters bodyValues) { if ((headValues != null && !headValues.validate()) || (bodyValues != null && !bodyValues.validate())) { throw new IllegalArgumentException(); } StringBuffer sb = new StringBuffer(LEFT_ANGLE_BRACKET + "\r\n"); sb.append("\t\"Request\"" + COLON + LEFT_ANGLE_BRACKET + "\r\n"); sb.append("\t\t\"head\"" + COLON + LEFT_ANGLE_BRACKET + "\r\n"); for (int i = 0; i < headValues.size(); i++) { sb.append( "\t\t\t\"" + headValues.getKey(i).toLowerCase() + "\"" + COLON).append( JSONUtil.object2json(headValues.getValue(headValues .getKey(i)))); if (i != headValues.size() - 1) { sb.append(","); } sb.append("\r\n"); } sb.append("\t\t" + RIGHT_ANGLE_BRACKET + ",\r\n"); sb.append("\t\t\"body\"" + COLON + LEFT_ANGLE_BRACKET + "\r\n"); for (int i = 0; i < bodyValues.size(); i++) { sb.append( "\t\t\t\"" + bodyValues.getKey(i).toLowerCase() + "\"" + COLON).append( JSONUtil.object2json(bodyValues.getValue(bodyValues .getKey(i)))); if (i != bodyValues.size() - 1) { sb.append(","); } sb.append("\r\n"); } sb.append("\t\t" + RIGHT_ANGLE_BRACKET + "\r\n"); sb.append("\t" + RIGHT_ANGLE_BRACKET + "\r\n"); sb.append(RIGHT_ANGLE_BRACKET); headValues.clear(); bodyValues.clear(); return sb.toString(); } }
JSONUtil
package com.example.uploadphoto2server; import java.lang.reflect.Field; import java.math.BigDecimal; import java.math.BigInteger; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import com.google.gson.Gson; public class JSONUtil { /** 對象轉換為json */ public static String object2json(Object obj) { StringBuilder json = new StringBuilder(); if (obj == null) { json.append("\"\""); } else if (obj instanceof String || obj instanceof Integer || obj instanceof Float || obj instanceof Boolean || obj instanceof Short || obj instanceof Double || obj instanceof Long || obj instanceof BigDecimal || obj instanceof BigInteger || obj instanceof Byte) { json.append("\"").append(string2json(obj.toString())).append("\""); } else if (obj instanceof Object[]) { json.append(array2json((Object[]) obj)); } else if (obj instanceof List) { json.append(list2json((List) obj)); } else if (obj instanceof Map) { json.append(map2json((Map) obj)); } else if (obj instanceof Set) { json.append(set2json((Set) obj)); } else { json.append(bean2json(obj)); } return json.toString(); } /** 對象轉換為json */ public static String bean2json(Object bean) { Gson gson = new Gson(); return gson.toJson(bean); } /** List轉換為json */ public static String list2json(List list) { StringBuilder json = new StringBuilder(); json.append("["); if (list != null && list.size() > 0) { for (Object obj : list) { json.append(object2json(obj)); json.append(","); } json.setCharAt(json.length() - 1, ']'); } else { json.append("]"); } return json.toString(); } /** 數組轉換為json */ public static String array2json(Object[] array) { StringBuilder json = new StringBuilder(); json.append("["); if (array != null && array.length > 0) { for (Object obj : array) { json.append(object2json(obj)); json.append(","); } json.setCharAt(json.length() - 1, ']'); } else { json.append("]"); } return json.toString(); } /** map轉換為json */ public static String map2json(Map map) { StringBuilder json = new StringBuilder(); json.append("{"); if (map != null && map.size() > 0) { for (Object key : map.keySet()) { json.append(object2json(key)); json.append(":"); json.append(object2json(map.get(key))); json.append(","); } json.setCharAt(json.length() - 1, '}'); } else { json.append("}"); } return json.toString(); } /** set轉換為json */ public static String set2json(Set set) { StringBuilder json = new StringBuilder(); json.append("["); if (set != null && set.size() > 0) { for (Object obj : set) { json.append(object2json(obj)); json.append(","); } json.setCharAt(json.length() - 1, ']'); } else { json.append("]"); } return json.toString(); } public static String string2json(String s) { if (s == null) return ""; StringBuilder sb = new StringBuilder(); for (int i = 0; i < s.length(); i++) { char ch = s.charAt(i); switch (ch) { case '"': sb.append("\\\""); break; case '\\': sb.append("\\\\"); break; case '\b': sb.append("\\b"); break; case '\f': sb.append("\\f"); break; case '\n': sb.append("\\n"); break; case '\r': sb.append("\\r"); break; case '\t': sb.append("\\t"); break; case '/': sb.append("\\/"); break; default: if (ch >= '\u0000' && ch <= '\u001F') { String ss = Integer.toHexString(ch); sb.append("\\u"); for (int k = 0; k < 4 - ss.length(); k++) { sb.append('0'); } sb.append(ss.toUpperCase()); } else { sb.append(ch); } } } return sb.toString(); } /** * 對象轉map * * @param obj * @return */ public static MapobjToMap(Object obj) { Map map = new HashMap (); try { /* * BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass()); * PropertyDescriptor[] propertyDescriptors = beanInfo * .getPropertyDescriptors(); for (PropertyDescriptor property : * propertyDescriptors) { String key = property.getName(); // * 過濾class屬性 if (!key.equals("class")) { // 得到property對應的getter方法 * Method getter = property.getReadMethod(); Object value = * getter.invoke(obj); map.put(key, value); } } */ Field[] fields = obj.getClass().getDeclaredFields(); for (Field field : fields) { String key = field.getName(); boolean accessFlag = field.isAccessible(); field.setAccessible(true); Object val = field.get(obj); if (val == null) { val = ""; } map.put(key, val); field.setAccessible(accessFlag); } } catch (Exception e) { e.printStackTrace(); } return map; } }
JsonParameters
package com.example.uploadphoto2server; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class JsonParameters { private Listlist = null; private Map map = null; public JsonParameters() { list = new ArrayList (); map = new HashMap (); } public void add(String key, Object value) { if(list.contains(key)){ list.remove(key); } list.add(key); map.put(key, value); } public String getKey(int id) { return list.get(id); } public Object getValue(String key) { return map.get(key); } public int size(){ return list.size(); } public boolean validate(){ return list.size() == map.size(); } public void clear(){ list.clear(); map.clear(); //list = null; //map = null; } }
本文講述了Android使用國內鏡像在線更新SDK的方法。分享給大家供大家參考,具體如下:什麼是Android SDK:SDK:(software development
博主在剛剛在學習過程中發現了一個關於android往sdcard讀寫的問題, 配置了該配置的提示無讀寫權限。 在AndroidManifest.xml文件中配置清單如下
在開發中經常會有一些需求,比如顯示頭像,顯示一些特殊的需求,將圖片顯示成圓角或者圓形或者其他的一些形狀。但是往往我們手上的圖片或者從服務器獲取到的圖片都是方形的。這時候就
Activity的生命周期圖2 Android生命周期中涉及到的幾個過程 1.啟動Activity:系統會先調用onCreate方法,然後調用onStart方法,最後