- Map map = new HashMap();
- map.put("source", "appkey");//改成自己的key
- map.put("status", txt);
- postImg("http://api.t.sina.com.cn/statuses/upload.json",map,Environment.getExternalStorageDirectory()+ "/temp.jpg"
- ,"帐号名字","密码");
- /**
- * 直接通过HTTP协议提交数据到服务器,实现表单提交功能
- * @param actionUrl 上传路径
- * @param params 请求参数 key为参数名,value为参数值
- * @param filename 上传文件
- * @param username 用户名
- * @param password 密码
- */
- private void postImg(String actionUrl,Map<String, String> params, String filename,String username,String password) {
- try {
- String BOUNDARY = "--------------et567z"; //数据分隔线
- String MULTIPART_FORM_DATA = "Multipart/form-data";
- URL url = new URL(actionUrl);
- HttpURLConnection conn = (HttpURLConnection) url.openConnection();
- conn.setDoInput(true);//允许输入
- conn.setDoOutput(true);//允许输出
- conn.setUseCaches(false);//不使用Cache
- conn.setRequestMethod("POST");
- conn.setRequestProperty("Connection", "Keep-Alive");
- conn.setRequestProperty("Charset", "UTF-8");
- conn.setRequestProperty("Content-Type", MULTIPART_FORM_DATA + ";boundary=" + BOUNDARY);
- String usernamePassword=username+":"+password;
- conn.setRequestProperty("Authorization","Basic "+new String(SecBase64.encode(usernamePassword.getBytes())));
- StringBuilder sb = new StringBuilder();
- //上传的表单参数部分,格式请参考文章
- for (Map.Entry<String, String> entry : params.entrySet()) {//构建表单字段内容
- sb.append("--");
- sb.append(BOUNDARY);
- sb.append("\r\n");
- sb.append("Content-Disposition: form-data; name=\""+ entry.getKey() + "\"\r\n\r\n");
- sb.append(entry.getValue());
- sb.append("\r\n");
- }
- // System.out.println(sb.toString());
- DataOutputStream outStream = new DataOutputStream(conn.getOutputStream());
- outStream.write(sb.toString().getBytes());//发送表单字段数据
- byte[] content = readFileImage(filename);
- //上传的文件部分,格式请参考文章
- //System.out.println("content:"+content.toString());
- StringBuilder split = new StringBuilder();
- split.append("--");
- split.append(BOUNDARY);
- split.append("\r\n");
- split.append("Content-Disposition: form-data;name=\"pic\";filename=\"temp.jpg\"\r\n");
- split.append("Content-Type: image/jpg\r\n\r\n");
- System.out.println(split.toString());
- outStream.write(split.toString().getBytes());
- outStream.write(content, 0, content.length);
- outStream.write("\r\n".getBytes());
- byte[] end_data = ("--" + BOUNDARY + "--\r\n").getBytes();//数据结束标志
- outStream.write(end_data);
- outStream.flush();
- int cah = conn.getResponseCode();
- // if (cah != 200) throw new RuntimeException("请求url失败:"+cah);
- if(cah == 200)//如果发布成功则提示成功
- {
- /*读返回数据*/
- //String strResult = EntityUtils.toString(httpResponse.getEntity());
- new AlertDialog.Builder(Main.this)
- // Main.this视情况而定,这个一般是指当前显示的Activity对应的XML视窗。
- .setTitle("")// 设置对话框的标题
- .setPositiveButton("确定",// 设置对话框的确认按钮
- new DialogInterface.OnClickListener() {// 设置确认按钮的事件
- public void onClick(DialogInterface dialog, int which) {
- }})
- .setMessage(" 发布成功 ")// 设置对话框的内容
- .show();
- }
- else if(cah == 400)
- {
- new AlertDialog.Builder(Main.this)
- // Main.this视情况而定,这个一般是指当前显示的Activity对应的XML视窗。
- .setTitle("")// 设置对话框的标题
- .setPositiveButton("确定",// 设置对话框的确认按钮
- new DialogInterface.OnClickListener() {// 设置确认按钮的事件
- public void onClick(DialogInterface dialog, int which) {
- }})
- .setMessage(" 发布失败 \n 不可连续发布相同内容 ")// 设置对话框的内容
- .show();
- }else{
- throw new RuntimeException("请求url失败:"+cah);
- }
- // InputStream is = conn.getInputStream();
- // int ch;
- // StringBuilder b = new StringBuilder();
- // while( (ch = is.read()) != -1 ){
- // b.append((char)ch);
- // }
- outStream.close();
- conn.disconnect();
- }
- catch (IOException e)
- {
- e.printStackTrace();
- }
- catch (Exception e)
- {
- e.printStackTrace();
- }
- }
- public static byte[] readFileImage(String filename) throws IOException {
- BufferedInputStream bufferedInputStream = new BufferedInputStream(
- new FileInputStream(filename));
- int len = bufferedInputStream.available();
- byte[] bytes = new byte[len];
- int r = bufferedInputStream.read(bytes);
- if (len != r) {
- bytes = null;
- throw new IOException("读取文件不正确");
- }
- bufferedInputStream.close();
- return bytes;
- }
2、只发文字
- //POST发布文本信息
- public void sendMsg(String status,String username,String password){
- HttpClient httpclient = new DefaultHttpClient();
- HttpPost httppost = new HttpPost("http://api.t.sina.com.cn/statuses/update.json");
- //NameValuePair实现请求参数的封装
- List params = new ArrayList ();
- params.add(new BasicNameValuePair("source", "4016954419"));
- params.add(new BasicNameValuePair("status", status));
- try
- {
- //添加请求参数到请求对象
- httppost.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
- httppost.getParams().setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, false);
- String data=username+":"+password;
- httppost.addHeader("Authorization","Basic "+new String(SecBase64.encode(data.getBytes())));
- httppost.addHeader("Content-Type", "application/x-www-form-urlencoded");
- //发送请求并等待响应
- HttpResponse httpResponse = new DefaultHttpClient().execute(httppost);
- //若状态码为200 ok
- if(httpResponse.getStatusLine().getStatusCode() == 200)
- {
- //读返回数据
- //String strResult = EntityUtils.toString(httpResponse.getEntity());
- new AlertDialog.Builder(Main.this)
- // Main.this视情况而定,这个一般是指当前显示的Activity对应的XML视窗。
- .setTitle("")// 设置对话框的标题
- .setPositiveButton("确定",// 设置对话框的确认按钮
- new DialogInterface.OnClickListener() {// 设置确认按钮的事件
- public void onClick(DialogInterface dialog, int which) {
- }})
- .setMessage(" 发布成功 ")// 设置对话框的内容
- .show();
- }
- else if(httpResponse.getStatusLine().getStatusCode() == 400)
- {
- new AlertDialog.Builder(Main.this)
- // Main.this视情况而定,这个一般是指当前显示的Activity对应的XML视窗。
- .setTitle("")// 设置对话框的标题
- .setPositiveButton("确定",// 设置对话框的确认按钮
- new DialogInterface.OnClickListener() {// 设置确认按钮的事件
- public void onClick(DialogInterface dialog, int which) {
- }})
- .setMessage(" 发布失败 \n 不可连续发布相同内容 ")// 设置对话框的内容
- .show();
- }
- }
- catch (ClientProtocolException e)
- {
- e.printStackTrace();
- et.setText(et.getText()+" Error1:"+e.getMessage());
- }
- catch (IOException e)
- {
- e.printStackTrace();
- et.setText(et.getText()+" Error2:"+e.getMessage());
- }
- catch (Exception e)
- {
- e.printStackTrace();
- et.setText(et.getText()+" Error3:"+e.getMessage());
- }
- }