android 向伺服器Get和Post請求的兩種方式,android向伺服器傳送檔案,自己組裝協議和藉助第三方開源,androidget

來源:互聯網
上載者:User

android 向伺服器Get和Post請求的兩種方式,android向伺服器傳送檔案,自己組裝協議和藉助第三方開源,androidget

/**  * @author intbird@163.com  * @time 20140606  */ package com.intbird.utils;import java.io.BufferedReader;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.net.HttpURLConnection;import java.net.URL;import java.net.URLConnection;import java.net.URLDecoder;import java.net.URLEncoder;import java.nio.charset.Charset;import java.util.ArrayList;import java.util.HashMap;import java.util.Iterator;import java.util.Map;import org.apache.http.HttpResponse;import org.apache.http.client.HttpClient;import org.apache.http.client.methods.HttpGet;import org.apache.http.client.methods.HttpPost;import org.apache.http.entity.mime.MultipartEntity;import org.apache.http.entity.mime.content.FileBody;import org.apache.http.entity.mime.content.StringBody;import org.apache.http.impl.client.DefaultHttpClient;import org.apache.http.util.EntityUtils;import android.graphics.Bitmap;import android.graphics.BitmapFactory;import android.os.Handler;import android.os.Message;public class ConnInternet {/** * 開始串連 */public static int HTTP_STATUS_START=0;/** * 串連過程出錯 */public static int HTTP_STATUS_ERROR=400;/** * 請求成功,返回資料 */public static int HTTP_STATUS_REULTOK=200;/** * 伺服器未響應 */public static int HTTP_STATUS_NORESP=500;/** * 普通GET請求 * @param api * @param callBack */public static void get1(final String api,final ConnInternetCallback callBack) {final Handler handler=getHandle(api, callBack);new Thread(){@Overridepublic void run() {Message msg=handler.obtainMessage(HTTP_STATUS_START, "開始串連");try {URL url = new URL(api);HttpURLConnection urlConn =  (HttpURLConnection) url.openConnection();int resCode=urlConn.getResponseCode();if(resCode!=HTTP_STATUS_REULTOK){msg.what=HTTP_STATUS_NORESP;msg.obj=resCode;handler.sendMessage(msg);return ;}InputStreamReader inStream=new InputStreamReader(urlConn.getInputStream());BufferedReader buffer=new BufferedReader(inStream);String result="";String inputLine=null;while((inputLine=buffer.readLine())!=null){result+=inputLine;}msg.what=HTTP_STATUS_REULTOK;    msg.obj=URLDecoder.decode(result,"UTF-8");    inStream.close();urlConn.disconnect();} catch (Exception ex) {msg.what=HTTP_STATUS_ERROR;    msg.obj=ex.getMessage().toString();}finally{handler.sendMessage(msg);}}}.start();}public void get3(final String api,final ConnInternetCallback callBack) {final Handler handler=getHandle(api, callBack);new Thread(){@Overridepublic void run() {Message msg=handler.obtainMessage(HTTP_STATUS_START, "開始串連");try {HttpGet httpGet=new HttpGet(api);HttpClient httpClient = new DefaultHttpClient();HttpResponse httpResp = httpClient.execute(httpGet);int resCode=httpResp.getStatusLine().getStatusCode();if(resCode!=HTTP_STATUS_REULTOK){msg.what=HTTP_STATUS_NORESP;msg.obj=resCode;handler.sendMessage(msg);return ;}msg.what=HTTP_STATUS_REULTOK;msg.obj= EntityUtils.toString(httpResp.getEntity());}catch (Exception e) {msg.what=HTTP_STATUS_ERROR;msg.obj= e.getMessage();}finally{handler.sendMessage(msg);}}}.start();}private static Handler getHandle(final String api,final ConnInternetCallback callBack){return new Handler() {@Overridepublic void handleMessage(Message message) {//不 在 這裡寫!callBack.callBack(message.what,api, message.obj.toString());}};}/** * 簡單類型,只進行文字資訊的POST; * @param api api地址 * @param params 僅欄位參數 * @param callBack 返回調用; */public static void post1(final String api,final HashMap<String,String> params,final ConnInternetCallback callBack){final Handler handler=getHandle(api, callBack);new Thread(){@Overridepublic void run() {Message msg=handler.obtainMessage(HTTP_STATUS_START,"開始串連");try {URL url=new URL(api);HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();urlConn.setDoInput(true);urlConn.setDoOutput(true);urlConn.setRequestMethod("POST");urlConn.setUseCaches(false);urlConn.setInstanceFollowRedirects(true);urlConn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");urlConn.setRequestProperty("Charset", "UTF-8");urlConn.connect();            DataOutputStream out = new DataOutputStream(urlConn.getOutputStream());              Iterator<String> iterator=params.keySet().iterator();            while(iterator.hasNext()){            String key= iterator.next();            String value= URLEncoder.encode(params.get(key),"UTF-8");            out.write((key+"="+value+"&").getBytes());              }            out.flush();              out.close();                      int resCode=urlConn.getResponseCode();if(resCode!=HTTP_STATUS_REULTOK){msg.what=HTTP_STATUS_NORESP;msg.obj=resCode;handler.sendMessage(msg);return ;}            String result="";            String readLine=null;            InputStreamReader inputStream=new InputStreamReader(urlConn.getInputStream());            BufferedReader bufferReader=new BufferedReader(inputStream);            while((readLine=bufferReader.readLine())!=null){            result+=readLine;            }            msg.what=HTTP_STATUS_REULTOK;        msg.obj=URLDecoder.decode(result,"UTF-8");            inputStream.close();            bufferReader.close();            urlConn.disconnect();}catch(Exception ex){msg.what=HTTP_STATUS_ERROR;    msg.obj=ex.getMessage().toString()+".";}finally{            handler.sendMessage(msg);}}}.start();}/** * 自訂文字和檔案傳輸通訊協定[樣本在函數結尾]; * @param apiUrl api地址 * @param mapParams 文字欄位參數 * @param listUpFiles 多檔案參數 * @param callBack 返回調用; */public static void post2(final String apiUrl,final HashMap<String,String> mapParams,final ArrayList<ConnInternetUploadFile> listUpFiles,ConnInternetCallback callBack){final Handler handler=getHandle(apiUrl, callBack);new Thread(new Runnable() {public void run() {Message msg=handler.obtainMessage(HTTP_STATUS_START, "開始串連");String BOUNDARY="———7d4a6454354fe54scd";String PREFIX="--";String LINE_END="\r\n";try{URL url=new URL(apiUrl);HttpURLConnection urlConn=(HttpURLConnection) url.openConnection();urlConn.setDoOutput(true);urlConn.setDoInput(true);urlConn.setUseCaches(false);urlConn.setRequestMethod("POST");urlConn.setRequestProperty("Connection", "Keep-Alive");urlConn.setRequestProperty("Charset", "UTF-8");urlConn.setRequestProperty("Content-Type","multipart/form-data ;boundary="+BOUNDARY);DataOutputStream outStream=new DataOutputStream(urlConn.getOutputStream());for(Map.Entry<String,String> entry:mapParams.entrySet()){StringBuilder sbParam=new StringBuilder();sbParam.append(PREFIX);sbParam.append(BOUNDARY);sbParam.append(LINE_END);sbParam.append("Content-Disposition:form-data;name=\""+ entry.getKey()+"\""+LINE_END);sbParam.append("Content-Transfer-Encoding: 8bit" + LINE_END);sbParam.append(LINE_END);sbParam.append(entry.getValue());sbParam.append(LINE_END);outStream.write(sbParam.toString().getBytes());}for(ConnInternetUploadFile file:listUpFiles){StringBuilder sbFile=new StringBuilder();sbFile.append(PREFIX);sbFile.append(BOUNDARY);sbFile.append(LINE_END);sbFile.append("Content-Disposition:form-data;name=\""+file.getFormname()+"\";filename=\""+file.getFileName()+"\""+LINE_END);sbFile.append("Content-type:"+file.getContentType()+"\""+LINE_END);outStream.write(sbFile.toString().getBytes());writeFileToOutStream(outStream,file.getFileUrl());outStream.write(LINE_END.getBytes("UTF-8"));}byte[] end_data=(PREFIX+BOUNDARY+PREFIX+LINE_END).getBytes("UTF-8");outStream.write(end_data);outStream.flush();outStream.close();          int resCode=urlConn.getResponseCode();if(resCode!=HTTP_STATUS_REULTOK){msg.what=HTTP_STATUS_NORESP;msg.obj=resCode;handler.sendMessage(msg);return ;}            String result="";            String readLine=null;            InputStreamReader inputStream=new InputStreamReader(urlConn.getInputStream());            BufferedReader bufferReader=new BufferedReader(inputStream);            while((readLine=bufferReader.readLine())!=null){            result+=readLine;            }            msg.what=HTTP_STATUS_REULTOK;        msg.obj=URLDecoder.decode(result,"UTF-8");        inputStream.close();            bufferReader.close();            urlConn.disconnect();}catch(Exception ex){msg.what=HTTP_STATUS_ERROR;    msg.obj=ex.getMessage().toString();}finally{            handler.sendMessage(msg);}}}).start();//HashMap<String,String> params=new HashMap<String, String>();//params.put("pid", fileHelper.getShareProf("PassportId"));//params.put("json",postJson(text));//ArrayList<UploadFile> uploadFiles=new ArrayList<UploadFile>();//if(url.length()>0){//UploadFile upfile=new UploadFile(url,url,"Images");//uploadFiles.add(upfile);//}//Internet.post(Api.api_messageCreate, params,uploadFiles,new InternetCallback() {//@Override//public void callBack(int msgWhat, String api, String result) {//if(msgWhat==Internet.HTTP_STATUS_OK){////跟新資料//adapter.notifyDataSetChanged();////顯示沒有資料//}else showToast("網路錯誤");//}//});}/** * 第三方Apache整合POST * @param url api地址 * @param mapParams 參數 * @param callBack */public static void post3(final String url, final HashMap<String,String> mapParams,final HashMap<String,String> mapFileInfo,ConnInternetCallback callBack) {final Handler handler=getHandle(url, callBack);new Thread() {@Overridepublic void run() {Message msg=handler.obtainMessage(HTTP_STATUS_START, "開始串連");try {HttpPost httpPost = new HttpPost(url);        //多類型;MultipartEntity multipartEntity = new MultipartEntity();          //欄位        Iterator<?> it=mapParams.keySet().iterator();        while(it.hasNext()){        String key=(String) it.next();        String value=mapParams.get(key);    multipartEntity.addPart(key,new StringBody(value,Charset.forName("UTF-8")));        }        //檔案        it=mapFileInfo.keySet().iterator();        while(it.hasNext()){        String key=(String)it.next();        String value=mapFileInfo.get(key);        multipartEntity.addPart(key, new FileBody(new File(value)));        }                httpPost.setEntity(multipartEntity); HttpClient httpClient = new DefaultHttpClient();HttpResponse httpResp = httpClient.execute(httpPost);int resCode=httpResp.getStatusLine().getStatusCode();if(resCode!=HTTP_STATUS_REULTOK){msg.what=HTTP_STATUS_NORESP;msg.obj=resCode;handler.sendMessage(msg);return ;}msg.what=HTTP_STATUS_REULTOK;msg.obj= EntityUtils.toString(httpResp.getEntity());}catch (Exception e) {msg.what=HTTP_STATUS_ERROR;msg.obj= e.getMessage();}finally{handler.sendMessage(msg);}}}.start();}public static Bitmap loadBitmapFromNet(String imgUrl,BitmapFactory.Options options){Bitmap bitmap = null;URL imageUrl = null;if (imgUrl == null || imgUrl.length() == 0) return null;try {imageUrl = new URL(imgUrl);URLConnection conn = imageUrl.openConnection();conn.setDoInput(true);conn.connect();InputStream is = conn.getInputStream();int length = conn.getContentLength();if (length != -1) {byte[] imgData = new byte[length];byte[] temp = new byte[512];int readLen = 0;int destPos = 0;while ((readLen = is.read(temp)) != -1) {System.arraycopy(temp, 0, imgData, destPos, readLen);destPos += readLen;}bitmap = BitmapFactory.decodeByteArray(imgData, 0, imgData.length,options);options.inJustDecodeBounds=false;bitmap = BitmapFactory.decodeByteArray(imgData, 0, imgData.length,options);}} catch (IOException e) {return null;}return bitmap;}public static void writeFileToOutStream(DataOutputStream outStream,String url){try {InputStream inputStream = new FileInputStream(new File(url));int ch;while((ch=inputStream.read())!=-1){outStream.write(ch);}inputStream.close();}catch (Exception e) {e.printStackTrace();}}public interface ConnInternetCallback{public void callBack(int msgWhat,String api,String result);}public class ConnInternetUploadFile {private String filename;private String fileUrl;private String formname;private String contentType = "application/octet-stream";//image/jpegpublic ConnInternetUploadFile(String filename, String fileUrl, String formname) {this.filename = filename;this.fileUrl=fileUrl;this.formname = formname;}public String getFileUrl() {return fileUrl;}public void setFileUrl(String url) {this.fileUrl=url;}public String getFileName() {return filename;}public void setFileName(String filename) {this.filename = filename;}public String getFormname() {return formname;}public void setFormname(String formname) {this.formname = formname;}public String getContentType() {return contentType;}public void setContentType(String contentType) {this.contentType = contentType;}}}


android 怎把map傳給後台伺服器,後台伺服器要怎接收?是把map放在post本文裡面?

轉化為 json 字串 ,然後直接去json
 
對於android向J2EE伺服器發送資料怎接受的問題

你想說什麼,從GET改成POST,伺服器不用改變,用request.getParameter()就可以獲得POST表單裡的資料。
POST的參數是不會寫在URL上的,可能你雖然用了POST,但是你的參數仍然是和GET方式一樣,寫在了URL上。POST方法是安全的。
 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.