Androidはhttppostを通じてテキストファイルをサーバーにアップロードする実例コードです。


余計な話はしないで、直接みんなにキーコードを貼りました。

/**
*             log  
* @param urlstr    url 
* @param uploadFile log      
* /mnt/shell/emulated/0/LOG/LOG.log 
* @param newName log      LOG.log
* @return
*/
public static void httpPost(Activity activity,String urlstr,String uploadFile,String newName) {
LogUtil.info("getEhttpPostt", "urlstr="+urlstr+";uploadFile="+uploadFile+";newName="+newName,"i");
String end = "\r
"; String twoHyphens = "--"; String boundary = "*****";// int TIME_OUT = 10*1000; // HttpURLConnection con = null; DataOutputStream ds = null; InputStream is = null; try { URL url = new URL(urlstr); con = (HttpURLConnection) url.openConnection(); con.setReadTimeout(TIME_OUT); con.setConnectTimeout(TIME_OUT); /* Input、Output, Cache */ con.setDoInput(true); con.setDoOutput(true); con.setUseCaches(false); // http con.setRequestMethod("POST");// con.setRequestProperty("Connection", "Keep-Alive");// TCP con.setRequestProperty("Charset", "UTF-8");// con.setRequestProperty("Content-Type",//multipart/form-data "multipart/form-data;boundary=" + boundary); ds = new DataOutputStream(con.getOutputStream()); ds.writeBytes(twoHyphens + boundary + end); ds.writeBytes("Content-Disposition: form-data; " + "name=\"stblog\";filename=\"" + newName + "\"" + end); ds.writeBytes(end); // FileInputStream FileInputStream fStream = new FileInputStream(uploadFile); /* 1024bytes */ int bufferSize = 1024; byte[] buffer = new byte[bufferSize]; int length = -1; /* */ while ((length = fStream.read(buffer)) != -1) { /* DataOutputStream */ ds.write(buffer, 0, length); } ds.writeBytes(end); ds.writeBytes(twoHyphens + boundary + twoHyphens + end);// fStream.close(); ds.flush(); /* Response */ is = con.getInputStream(); int ch; StringBuffer b = new StringBuffer(); while ((ch = is.read()) != -1) { b.append((char) ch); } /* Response Dialog */ showDialog(activity,true,uploadFile," " + b.toString().trim()); } catch (Exception e) { showDialog(activity,false,uploadFile," " + e); }finally { /* DataOutputStream */ if(ds!=null){ try { ds.close(); } catch (IOException e) { e.printStackTrace(); } } if (is != null) { try { is.close(); } catch (IOException e) { e.printStackTrace(); } } if (con != null) { con.disconnect(); } } } /* Dialog method */ private static void showDialog(final Activity activity,final Boolean isSuccess,final String uploadFile,final String mess) { activity.runOnUiThread(new Runnable() { @Override public void run() { new AlertDialog.Builder(activity).setTitle("Message") .setMessage(mess) .setNegativeButton(" ", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { File file = new File(uploadFile); if(file.exists()&&isSuccess){// file.delete(); Toast.makeText(activity, "log ", Toast.LENGTH_SHORT).show(); } } }).show(); } }); }
以上は小编で绍介したAndroidがhttppostを通じてテキストファイルをサーバーにアップロードした実例コードです。コードは分かりやすく、コメントが付いています。ここでも私たちのサイトを応援してくれてありがとうございます。