新浪微博Android 客户端通过HTTP POST发布图片和文字源代码

 

目录(?)[+]

 

 

1、发送图片+文字

要特别注意,图片的文件名要为 pic 才会被新浪接收。

 

  1.           Map map = new HashMap();  
  2. map.put("source""appkey");//改成自己的key  
  3. map.put("status", txt);  
  4. postImg("http://api.t.sina.com.cn/statuses/upload.json",map,Environment.getExternalStorageDirectory()+ "/temp.jpg"  
  5.                 ,"帐号名字","密码");  
 

 

 

 

  1.              /** 
  2.  * 直接通过HTTP协议提交数据到服务器,实现表单提交功能 
  3.  * @param actionUrl 上传路径 
  4.  * @param params 请求参数 key为参数名,value为参数值 
  5.  * @param filename 上传文件 
  6.  * @param username 用户名 
  7.  * @param password 密码 
  8.  */  
  9. private void postImg(String actionUrl,Map<String, String> params, String  filename,String username,String password) {  
  10.     try {  
  11.         String BOUNDARY = "--------------et567z"//数据分隔线  
  12.         String MULTIPART_FORM_DATA = "Multipart/form-data";    
  13.         URL url = new URL(actionUrl);  
  14.         HttpURLConnection conn = (HttpURLConnection) url.openConnection();   
  15.         conn.setDoInput(true);//允许输入  
  16.         conn.setDoOutput(true);//允许输出  
  17.         conn.setUseCaches(false);//不使用Cache  
  18.         conn.setRequestMethod("POST");  
  19.         conn.setRequestProperty("Connection""Keep-Alive");  
  20.         conn.setRequestProperty("Charset""UTF-8");  
  21.         conn.setRequestProperty("Content-Type", MULTIPART_FORM_DATA + ";boundary=" + BOUNDARY);  
  22.         String usernamePassword=username+":"+password;  
  23.         conn.setRequestProperty("Authorization","Basic "+new String(SecBase64.encode(usernamePassword.getBytes())));  
  24.         StringBuilder sb = new StringBuilder();    
  25.         //上传的表单参数部分,格式请参考文章  
  26.         for (Map.Entry<String, String> entry : params.entrySet()) {//构建表单字段内容  
  27.             sb.append("--");  
  28.             sb.append(BOUNDARY);  
  29.             sb.append("/r/n");  
  30.             sb.append("Content-Disposition: form-data; name=/""+ entry.getKey() + "/"/r/n/r/n");  
  31.             sb.append(entry.getValue());  
  32.             sb.append("/r/n");  
  33.         }  
  34.         //            System.out.println(sb.toString());  
  35.         DataOutputStream outStream = new DataOutputStream(conn.getOutputStream());  
  36.         outStream.write(sb.toString().getBytes());//发送表单字段数据  
  37.         byte[] content = readFileImage(filename);  
  38.         //上传的文件部分,格式请参考文章  
  39.         //System.out.println("content:"+content.toString());  
  40.         StringBuilder split = new StringBuilder();  
  41.         split.append("--");  
  42.         split.append(BOUNDARY);  
  43.         split.append("/r/n");  
  44.         split.append("Content-Disposition: form-data;name=/"pic/";filename=/"temp.jpg/"/r/n");  
  45.         split.append("Content-Type: image/jpg/r/n/r/n");  
  46.         System.out.println(split.toString());  
  47.         outStream.write(split.toString().getBytes());  
  48.         outStream.write(content, 0, content.length);  
  49.         outStream.write("/r/n".getBytes());    
  50.         byte[] end_data = ("--" + BOUNDARY + "--/r/n").getBytes();//数据结束标志  
  51.         outStream.write(end_data);  
  52.         outStream.flush();  
  53.         int cah = conn.getResponseCode();  
  54.         //            if (cah != 200) throw new RuntimeException("请求url失败:"+cah);  
  55.         if(cah == 200)//如果发布成功则提示成功  
  56.         {  
  57.             /*读返回数据*/  
  58.             //String strResult = EntityUtils.toString(httpResponse.getEntity());   
  59.             new AlertDialog.Builder(Main.this)  
  60.             // Main.this视情况而定,这个一般是指当前显示的Activity对应的XML视窗。  
  61.             .setTitle("")// 设置对话框的标题  
  62.             .setPositiveButton("确定",// 设置对话框的确认按钮  
  63.                     new DialogInterface.OnClickListener() {// 设置确认按钮的事件  
  64.                 public void onClick(DialogInterface dialog, int which) {  
  65.                 }})  
  66.                 .setMessage(" 发布成功 ")// 设置对话框的内容  
  67.                 .show();  
  68.         }  
  69.         else if(cah == 400)  
  70.         {  
  71.             new AlertDialog.Builder(Main.this)  
  72.             // Main.this视情况而定,这个一般是指当前显示的Activity对应的XML视窗。  
  73.             .setTitle("")// 设置对话框的标题  
  74.             .setPositiveButton("确定",// 设置对话框的确认按钮  
  75.                     new DialogInterface.OnClickListener() {// 设置确认按钮的事件  
  76.                 public void onClick(DialogInterface dialog, int which) {  
  77.                 }})  
  78.                 .setMessage(" 发布失败  /n 不可连续发布相同内容 ")// 设置对话框的内容  
  79.                 .show();  
  80.         }else{  
  81.             throw new RuntimeException("请求url失败:"+cah);  
  82.         }   
  83.         //            InputStream is = conn.getInputStream();  
  84.         //            int ch;  
  85.         //            StringBuilder b = new StringBuilder();  
  86.         //            while( (ch = is.read()) != -1 ){  
  87.         //                b.append((char)ch);  
  88.         //            }  
  89.         outStream.close();  
  90.         conn.disconnect();  
  91.     }  
  92.     catch (IOException e)  
  93.     {  
  94.         e.printStackTrace();   
  95.     }  
  96.     catch (Exception e)  
  97.     {  
  98.         e.printStackTrace();    
  99.     }    
  100. }  
  101.             public static byte[] readFileImage(String filename) throws IOException {  
  102.     BufferedInputStream bufferedInputStream = new BufferedInputStream(  
  103.             new FileInputStream(filename));  
  104.     int len = bufferedInputStream.available();  
  105.     byte[] bytes = new byte[len];  
  106.     int r = bufferedInputStream.read(bytes);  
  107.     if (len != r) {  
  108.         bytes = null;  
  109.         throw new IOException("读取文件不正确");  
  110.     }  
  111.     bufferedInputStream.close();  
  112.     return bytes;  
  113. }  
 

 

 

2、只发文字

  1. //POST发布文本信息  
  2.    public  void sendMsg(String status,String username,String password){  
  3.     HttpClient httpclient = new DefaultHttpClient();  
  4.        HttpPost httppost = new HttpPost("http://api.t.sina.com.cn/statuses/update.json");  
  5.         //NameValuePair实现请求参数的封装  
  6.         List  params = new ArrayList ();  
  7.         params.add(new BasicNameValuePair("source""4016954419"));  
  8.         params.add(new BasicNameValuePair("status", status));  
  9.         try  
  10.         {   
  11.           //添加请求参数到请求对象  
  12.             httppost.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));  
  13.             httppost.getParams().setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, false);   
  14.             String data=username+":"+password;  
  15.             httppost.addHeader("Authorization","Basic "+new String(SecBase64.encode(data.getBytes())));  
  16.             httppost.addHeader("Content-Type""application/x-www-form-urlencoded");  
  17.           //发送请求并等待响应  
  18.           HttpResponse httpResponse = new DefaultHttpClient().execute(httppost);  
  19.           //若状态码为200 ok  
  20.           if(httpResponse.getStatusLine().getStatusCode() == 200)  
  21.           {  
  22.             //读返回数据  
  23.             //String strResult = EntityUtils.toString(httpResponse.getEntity());   
  24.             new AlertDialog.Builder(Main.this)  
  25.             // Main.this视情况而定,这个一般是指当前显示的Activity对应的XML视窗。  
  26.             .setTitle("")// 设置对话框的标题  
  27.             .setPositiveButton("确定",// 设置对话框的确认按钮  
  28.             new DialogInterface.OnClickListener() {// 设置确认按钮的事件  
  29.                 public void onClick(DialogInterface dialog, int which) {  
  30.             }})  
  31.             .setMessage(" 发布成功 ")// 设置对话框的内容  
  32.             .show();  
  33.           }  
  34.           else if(httpResponse.getStatusLine().getStatusCode() == 400)  
  35.           {  
  36.               new AlertDialog.Builder(Main.this)  
  37.                 // Main.this视情况而定,这个一般是指当前显示的Activity对应的XML视窗。  
  38.                 .setTitle("")// 设置对话框的标题  
  39.                 .setPositiveButton("确定",// 设置对话框的确认按钮  
  40.             new DialogInterface.OnClickListener() {// 设置确认按钮的事件  
  41.                 public void onClick(DialogInterface dialog, int which) {  
  42.             }})  
  43.                 .setMessage(" 发布失败  /n 不可连续发布相同内容 ")// 设置对话框的内容  
  44.                 .show();  
  45.           }   
  46.         }  
  47.         catch (ClientProtocolException e)  
  48.         {  
  49.           e.printStackTrace();  
  50.           et.setText(et.getText()+" Error1:"+e.getMessage());  
  51.         }  
  52.         catch (IOException e)  
  53.         {  
  54.           e.printStackTrace();  
  55.           et.setText(et.getText()+" Error2:"+e.getMessage());  
  56.         }  
  57.         catch (Exception e)  
  58.         {  
  59.           e.printStackTrace();  
  60.           et.setText(et.getText()+" Error3:"+e.getMessage());  
  61.         }    
  62.  }  
 

3、加密类 SecBase64.java

 

  1. package wizzer.cn.app;  
  2. public class SecBase64 {  
  3. private static final byte[] encodingTable = { (byte'A', (byte'B',  
  4.     (byte'C', (byte'D', (byte'E', (byte'F', (byte'G',  
  5.     (byte'H', (byte'I', (byte'J', (byte'K', (byte'L',  
  6.     (byte'M', (byte'N', (byte'O', (byte'P', (byte'Q',  
  7.     (byte'R', (byte'S', (byte'T', (byte'U', (byte'V',  
  8.     (byte'W', (byte'X', (byte'Y', (byte'Z', (byte'a',  
  9.     (byte'b', (byte'c', (byte'd', (byte'e', (byte'f',  
  10.     (byte'g', (byte'h', (byte'i', (byte'j', (byte'k',  
  11.     (byte'l', (byte'm', (byte'n', (byte'o', (byte'p',  
  12.     (byte'q', (byte'r', (byte's', (byte't', (byte'u',  
  13.     (byte'v', (byte'w', (byte'x', (byte'y', (byte'z',  
  14.     (byte'0', (byte'1', (byte'2', (byte'3', (byte'4',  
  15.     (byte'5', (byte'6', (byte'7', (byte'8', (byte'9',  
  16.     (byte'+', (byte'/' };  
  17. private static final byte[] decodingTable;  
  18. static {  
  19.    decodingTable = new byte[128];  
  20.    for (int i = 0; i < 128; i++) {  
  21.     decodingTable[i] = (byte) -1;  
  22.    }  
  23.    for (int i = 'A'; i <= 'Z'; i++) {  
  24.     decodingTable[i] = (byte) (i - 'A');  
  25.    }  
  26.    for (int i = 'a'; i <= 'z'; i++) {  
  27.     decodingTable[i] = (byte) (i - 'a' + 26);  
  28.    }  
  29.    for (int i = '0'; i <= '9'; i++) {  
  30.     decodingTable[i] = (byte) (i - '0' + 52);  
  31.    }  
  32.    decodingTable['+'] = 62;  
  33.    decodingTable['/'] = 63;  
  34. }  
  35. //加密  
  36. public static byte[] encode(byte[] data) {  
  37.    byte[] bytes;  
  38.    int modulus = data.length % 3;  
  39.    if (modulus == 0) {  
  40.     bytes = new byte[(4 * data.length) / 3];  
  41.    } else {  
  42.     bytes = new byte[4 * ((data.length / 3) + 1)];  
  43.    }  
  44.    int dataLength = (data.length - modulus);  
  45.    int a1;  
  46.    int a2;  
  47.    int a3;  
  48.    for (int i = 0, j = 0; i < dataLength; i += 3, j += 4) {  
  49.     a1 = data[i] & 0xff;  
  50.     a2 = data[i + 1] & 0xff;  
  51.     a3 = data[i + 2] & 0xff;  
  52.     bytes[j] = encodingTable[(a1 >>> 2) & 0x3f];  
  53.     bytes[j + 1] = encodingTable[((a1 << 4) | (a2 >>> 4)) & 0x3f];  
  54.     bytes[j + 2] = encodingTable[((a2 << 2) | (a3 >>> 6)) & 0x3f];  
  55.     bytes[j + 3] = encodingTable[a3 & 0x3f];  
  56.    }  
  57.    int b1;  
  58.    int b2;  
  59.    int b3;  
  60.    int d1;  
  61.    int d2;  
  62.    switch (modulus) {  
  63.    case 0:  
  64.     break;  
  65.    case 1:  
  66.     d1 = data[data.length - 1] & 0xff;  
  67.     b1 = (d1 >>> 2) & 0x3f;  
  68.     b2 = (d1 << 4) & 0x3f;  
  69.     bytes[bytes.length - 4] = encodingTable[b1];  
  70.     bytes[bytes.length - 3] = encodingTable[b2];  
  71.     bytes[bytes.length - 2] = (byte'=';  
  72.     bytes[bytes.length - 1] = (byte'=';  
  73.     break;  
  74.    case 2:  
  75.     d1 = data[data.length - 2] & 0xff;  
  76.     d2 = data[data.length - 1] & 0xff;  
  77.     b1 = (d1 >>> 2) & 0x3f;  
  78.     b2 = ((d1 << 4) | (d2 >>> 4)) & 0x3f;  
  79.     b3 = (d2 << 2) & 0x3f;  
  80.     bytes[bytes.length - 4] = encodingTable[b1];  
  81.     bytes[bytes.length - 3] = encodingTable[b2];  
  82.     bytes[bytes.length - 2] = encodingTable[b3];  
  83.     bytes[bytes.length - 1] = (byte'=';  
  84.     break;  
  85.    }  
  86.    return bytes;  
  87. }  
  88. //解密  
  89. public static byte[] decode(byte[] data) {  
  90.    byte[] bytes;  
  91.    byte b1;  
  92.    byte b2;  
  93.    byte b3;  
  94.    byte b4;  
  95.    data = discardNonBase64Bytes(data);  
  96.    if (data[data.length - 2] == '=') {  
  97.     bytes = new byte[(((data.length / 4) - 1) * 3) + 1];  
  98.    } else if (data[data.length - 1] == '=') {  
  99.     bytes = new byte[(((data.length / 4) - 1) * 3) + 2];  
  100.    } else {  
  101.     bytes = new byte[((data.length / 4) * 3)];  
  102.    }  
  103.    for (int i = 0, j = 0; i < (data.length - 4); i += 4, j += 3) {  
  104.     b1 = decodingTable[data[i]];  
  105.     b2 = decodingTable[data[i + 1]];  
  106.     b3 = decodingTable[data[i + 2]];  
  107.     b4 = decodingTable[data[i + 3]];  
  108.     bytes[j] = (byte) ((b1 << 2) | (b2 >> 4));  
  109.     bytes[j + 1] = (byte) ((b2 << 4) | (b3 >> 2));  
  110.     bytes[j + 2] = (byte) ((b3 << 6) | b4);  
  111.    }  
  112.    if (data[data.length - 2] == '=') {  
  113.     b1 = decodingTable[data[data.length - 4]];  
  114.     b2 = decodingTable[data[data.length - 3]];  
  115.     bytes[bytes.length - 1] = (byte) ((b1 << 2) | (b2 >> 4));  
  116.    } else if (data[data.length - 1] == '=') {  
  117.     b1 = decodingTable[data[data.length - 4]];  
  118.     b2 = decodingTable[data[data.length - 3]];  
  119.     b3 = decodingTable[data[data.length - 2]];  
  120.     bytes[bytes.length - 2] = (byte) ((b1 << 2) | (b2 >> 4));  
  121.     bytes[bytes.length - 1] = (byte) ((b2 << 4) | (b3 >> 2));  
  122.    } else {  
  123.     b1 = decodingTable[data[data.length - 4]];  
  124.     b2 = decodingTable[data[data.length - 3]];  
  125.     b3 = decodingTable[data[data.length - 2]];  
  126.     b4 = decodingTable[data[data.length - 1]];  
  127.     bytes[bytes.length - 3] = (byte) ((b1 << 2) | (b2 >> 4));  
  128.     bytes[bytes.length - 2] = (byte) ((b2 << 4) | (b3 >> 2));  
  129.     bytes[bytes.length - 1] = (byte) ((b3 << 6) | b4);  
  130.    }  
  131.    return bytes;  
  132. }  
  133. //解密  
  134. public static byte[] decode(String data) {  
  135.    byte[] bytes;  
  136.    byte b1;  
  137.    byte b2;  
  138.    byte b3;  
  139.    byte b4;  
  140.    data = discardNonBase64Chars(data);  
  141.    if (data.charAt(data.length() - 2) == '=') {  
  142.     bytes = new byte[(((data.length() / 4) - 1) * 3) + 1];  
  143.    } else if (data.charAt(data.length() - 1) == '=') {  
  144.     bytes = new byte[(((data.length() / 4) - 1) * 3) + 2];  
  145.    } else {  
  146.     bytes = new byte[((data.length() / 4) * 3)];  
  147.    }  
  148.    for (int i = 0, j = 0; i < (data.length() - 4); i += 4, j += 3) {  
  149.     b1 = decodingTable[data.charAt(i)];  
  150.     b2 = decodingTable[data.charAt(i + 1)];  
  151.     b3 = decodingTable[data.charAt(i + 2)];  
  152.     b4 = decodingTable[data.charAt(i + 3)];  
  153.     bytes[j] = (byte) ((b1 << 2) | (b2 >> 4));  
  154.     bytes[j + 1] = (byte) ((b2 << 4) | (b3 >> 2));  
  155.     bytes[j + 2] = (byte) ((b3 << 6) | b4);  
  156.    }  
  157.    if (data.charAt(data.length() - 2) == '=') {  
  158.     b1 = decodingTable[data.charAt(data.length() - 4)];  
  159.     b2 = decodingTable[data.charAt(data.length() - 3)];  
  160.     bytes[bytes.length - 1] = (byte) ((b1 << 2) | (b2 >> 4));  
  161.    } else if (data.charAt(data.length() - 1) == '=') {  
  162.     b1 = decodingTable[data.charAt(data.length() - 4)];  
  163.     b2 = decodingTable[data.charAt(data.length() - 3)];  
  164.     b3 = decodingTable[data.charAt(data.length() - 2)];  
  165.     bytes[bytes.length - 2] = (byte) ((b1 << 2) | (b2 >> 4));  
  166.     bytes[bytes.length - 1] = (byte) ((b2 << 4) | (b3 >> 2));  
  167.    } else {  
  168.     b1 = decodingTable[data.charAt(data.length() - 4)];  
  169.     b2 = decodingTable[data.charAt(data.length() - 3)];  
  170.     b3 = decodingTable[data.charAt(data.length() - 2)];  
  171.     b4 = decodingTable[data.charAt(data.length() - 1)];  
  172.     bytes[bytes.length - 3] = (byte) ((b1 << 2) | (b2 >> 4));  
  173.     bytes[bytes.length - 2] = (byte) ((b2 << 4) | (b3 >> 2));  
  174.     bytes[bytes.length - 1] = (byte) ((b3 << 6) | b4);  
  175.    }  
  176.    return bytes;  
  177. }  
  178. private static byte[] discardNonBase64Bytes(byte[] data) {  
  179.    byte[] temp = new byte[data.length];  
  180.    int bytesCopied = 0;  
  181.    for (int i = 0; i < data.length; i++) {  
  182.     if (isValidBase64Byte(data[i])) {  
  183.      temp[bytesCopied++] = data[i];  
  184.     }  
  185.    }  
  186.    byte[] newData = new byte[bytesCopied];  
  187.    System.arraycopy(temp, 0, newData, 0, bytesCopied);  
  188.    return newData;  
  189. }  
  190. private static String discardNonBase64Chars(String data) {  
  191.    StringBuffer sb = new StringBuffer();  
  192.    int length = data.length();  
  193.    for (int i = 0; i < length; i++) {  
  194.     if (isValidBase64Byte((byte) (data.charAt(i)))) {  
  195.      sb.append(data.charAt(i));  
  196.     }  
  197.    }  
  198.    return sb.toString();  
  199. }  
  200. private static boolean isValidBase64Byte(byte b) {  
  201.    if (b == '=') {  
  202.     return true;  
  203.    } else if ((b < 0) || (b >= 128)) {  
  204.     return false;  
  205.    } else if (decodingTable[b] == -1) {  
  206.     return false;  
  207.    }  
  208.    return true;  
  209. }  
  210. //测试类  
  211. public static void main(String[] args) {  
  212.    String data = "wizzer@qq.com:etpass";  
  213.    byte[] result = SecBase64.encode(data.getBytes());// 加密  
  214.    System.out.println("Basic "+data);  
  215.    System.out.println("Basic "+new String(result));  
  216.    System.out.println(new String(SecBase64.decode(new String(result))));// 解密  
  217.    }  
  218. }  
 

 

 

 

 

posted @ 2014-03-10 10:20  huidaoli  阅读(385)  评论(0编辑  收藏  举报