Http post 发送图片+文字

  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.  }  
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值