使用HttpUrlConnection进行post 提交

package com.json;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.Gson;
import com.test.client.JSONObject;
import com.test.upload.Asset;
import com.test.upload.UploadRequest;
import com.test.upload.Video;

 

public class Test {

 /**
  * @param args
  * @throws Exception
  */
 public static void main(String[] args) throws Exception {
 
//   
//     OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
//     //wr.write(file);
//     wr.flush();
//     System.out.println("连接成功");
//    
//     /***json***/
//     Gson gson = new Gson();
//     User user1= new User("1245","000","2222","5555");
//   String json=  gson.toJson(user1);
//   System.out.println("---------------------"+json);
//  
//    User user= gson.fromJson(json, User.class);
//    System.out.println("*********************"+user.getStatus());
  //
    
  String loginParameters = "email=??&passwd=189.cn";
  String loginBack = Test.post(http://url, loginParameters);
  //获取登陆后返回的json字符串
  System.out.println("登陆后返回的json字符串"+loginBack);
  //json字符串转换成对象
  Gson gson = new Gson();
  User user= gson.fromJson(loginBack, User.class);
  System.out.println("获取token值:"+user.getToken());
  
  
  //创建空白视频 主要获取请求url 和视频 id
  String createVideoParameters="folderId=83587542191964162&title=我要创建视频啊";
  String createVideoBack =Test.post("url", createVideoParameters);
  System.out.println("空白视频返回的字符串"+createVideoBack);
  
  UploadRequest uploadRequest =gson.fromJson(createVideoBack, UploadRequest.class);
  System.out.println("获取上传视频文件的请求地址:"+uploadRequest.getUploadUrl());
  
  //上传视频文件 暂未实现
  
  
  
  
  Asset asset =gson.fromJson("上传之后返回的json字符串", Asset.class);
  System.out.println("视频播放id"+asset.getVideoId());
  String viddeoId=asset.getVideoId();
  
  //查询获取视频文件的地址 根据视频id查询 videoId
  String findVideo="videoId=86678073956630529";//viddeoId
  String findVideoBack=Test.get("url", findVideo);
  System.out.println("返回的json字符串:"+findVideoBack);
  Video video =gson.fromJson(findVideoBack, Video.class);
  System.out.println("视频播放地址:"+video.getVideoUrl());
  
  }
 
 //post 请求
 public static String post(String requestUrl,String parameters){
  StringBuffer buffer = new StringBuffer();
  URL url = null;

  HttpURLConnection conn = null;
  try {
   url = new URL(requestUrl);
   conn = (HttpURLConnection) url.openConnection();
   conn.setDoOutput(true);
   conn.setDoInput(true);
   conn.setRequestMethod("POST");// post

   conn.setUseCaches(false);
   conn.connect();
   // DataOutputStream out = new
   // DataOutputStream(conn.getOutputStream());
   PrintWriter outprint = new PrintWriter(new OutputStreamWriter(
     conn.getOutputStream(), "UTF-8"));
   outprint.write(parameters);
   outprint.flush();
   outprint.close();
   BufferedReader reader = new BufferedReader(new InputStreamReader(
     conn.getInputStream(), "UTF-8"));
   String line = "";
   while ((line = reader.readLine()) != null) {
    buffer.append(line);
   }
   reader.close();
  } catch (MalformedURLException e) {
   e.printStackTrace();
  } catch (ProtocolException e) {
   e.printStackTrace();

  } catch (UnsupportedEncodingException e) {
   e.printStackTrace();

  } catch (IOException e) {
   e.printStackTrace();
  }
    
  if (conn != null) {
   conn.disconnect();
  }

  return buffer.toString();

 }
 
 //get请求
 public static String get(String requestUrl,String parameters){
  StringBuffer buffer = new StringBuffer();
  URL url = null;

  HttpURLConnection conn = null;
  try {
   url = new URL(requestUrl);
   conn = (HttpURLConnection) url.openConnection();
   conn.setDoOutput(true);
   conn.setDoInput(true);
   conn.setRequestMethod("GET");// post

   conn.setUseCaches(false);
   conn.connect();
   // DataOutputStream out = new
   // DataOutputStream(conn.getOutputStream());
   PrintWriter outprint = new PrintWriter(new OutputStreamWriter(
     conn.getOutputStream(), "UTF-8"));
   outprint.write(parameters);
   outprint.flush();
   outprint.close();
   BufferedReader reader = new BufferedReader(new InputStreamReader(
     conn.getInputStream(), "UTF-8"));
   String line = "";
   while ((line = reader.readLine()) != null) {
    buffer.append(line);
   }
   reader.close();
  } catch (MalformedURLException e) {
   e.printStackTrace();
  } catch (ProtocolException e) {
   e.printStackTrace();

  } catch (UnsupportedEncodingException e) {
   e.printStackTrace();

  } catch (IOException e) {
   e.printStackTrace();
  }
    
  if (conn != null) {
   conn.disconnect();
  }

  return buffer.toString();

 }


}

 

//以下是 post get 和 提交文件上传文件的方法(修改版)

//post 请求
 public static String post(String requestUrl,String parameters){
  StringBuffer buffer = new StringBuffer();
  URL url = null;

  HttpURLConnection conn = null;
  try {
   url = new URL(requestUrl);
   conn = (HttpURLConnection) url.openConnection();
   conn.setDoOutput(true);
   conn.setDoInput(true);
   conn.setRequestMethod("POST");// post

   conn.setUseCaches(false);
   conn.connect();
   // DataOutputStream out = new
   // DataOutputStream(conn.getOutputStream());
   PrintWriter outprint = new PrintWriter(new OutputStreamWriter(
     conn.getOutputStream(), "UTF-8"));
   outprint.write(parameters);
   outprint.flush();
   outprint.close();
   BufferedReader reader = new BufferedReader(new InputStreamReader(
     conn.getInputStream(), "UTF-8"));
   String line = "";
   while ((line = reader.readLine()) != null) {
    buffer.append(line);
   }
   reader.close();
  } catch (MalformedURLException e) {
   e.printStackTrace();
  } catch (ProtocolException e) {
   e.printStackTrace();

  } catch (UnsupportedEncodingException e) {
   e.printStackTrace();

  } catch (IOException e) {
   e.printStackTrace();
  }
    
  if (conn != null) {
   conn.disconnect();
  }

  return buffer.toString();

 }
 
 //get请求
 public static String get(String requestUrl,String parameters){
  StringBuffer buffer = new StringBuffer();
  URL url = null;

  HttpURLConnection conn = null;
  try {
   url = new URL(requestUrl);
   conn = (HttpURLConnection) url.openConnection();
   conn.setDoOutput(true);
   conn.setDoInput(true);
   conn.setRequestMethod("GET");// post

   conn.setUseCaches(false);
   conn.connect();
   // DataOutputStream out = new
   // DataOutputStream(conn.getOutputStream());
   PrintWriter outprint = new PrintWriter(new OutputStreamWriter(
     conn.getOutputStream(), "UTF-8"));
   outprint.write(parameters);
   outprint.flush();
   outprint.close();
   BufferedReader reader = new BufferedReader(new InputStreamReader(
     conn.getInputStream(), "UTF-8"));
   String line = "";
   while ((line = reader.readLine()) != null) {
    buffer.append(line);
   }
   reader.close();
  } catch (MalformedURLException e) {
   e.printStackTrace();
  } catch (ProtocolException e) {
   e.printStackTrace();

  } catch (UnsupportedEncodingException e) {
   e.printStackTrace();

  } catch (IOException e) {
   e.printStackTrace();
  }
    
  if (conn != null) {
   conn.disconnect();
  }

  return buffer.toString();

 }
 
 //post 上传文件的的
 public static String postUrlWithData(String dispatchUrl, Map<String,String> paramMap,
   File file, Map<String,String> map ) {
//  JSONObject jsonObj = new JSONObject();
  StringBuffer buffer = new StringBuffer();

  HttpURLConnection conn = null;
  try {
   String BOUNDARY =  "---------7d4a6d158c9";
   String PREFIX = "--";
   String LINEND = "\r\n";
   String MULTIPART_FROM_DATA = "multipart/form-data";
   String CHARSET = "UTF-8";
   URL uri = new URL(dispatchUrl);
   conn = (HttpURLConnection) uri.openConnection();
   conn.setRequestMethod("POST");
   conn.setRequestProperty("connection", "keep-alive");
   conn.setRequestProperty("Charsert", "UTF-8");
   conn.setRequestProperty("Content-Type",
     new StringBuilder().append("multipart/form-data;boundary=")
       .append(BOUNDARY).toString());
   conn.setRequestProperty("User-Agent", "Mozilla/5.0(compatible)");
   conn.setRequestProperty("Accept", "*/*");
   conn.setDoInput(true);
   conn.setDoOutput(true);
   conn.connect();
   DataOutputStream outStream = new DataOutputStream(
     conn.getOutputStream());
   StringBuilder textParam = new StringBuilder();
   for (Map.Entry entry : paramMap.entrySet()) {
    textParam.append("--");
    textParam.append(BOUNDARY);
    textParam.append("\r\n");
    textParam.append(new StringBuilder()
      .append("Content-Disposition: form-data; name=\"")
      .append((String) entry.getKey()).append("\"")
      .append("\r\n").toString());
    textParam.append("Content-Type: text/plain; charset=UTF-8\r\n");
    textParam.append("Content-Transfer-Encoding: 8bit\r\n");
    textParam.append("\r\n");
    textParam.append(entry.getValue());
    textParam.append("\r\n");
   }
//   System.out.println(textParam.toString());
   outStream.write(textParam.toString().getBytes());
   outStream.flush();

   StringBuilder sb1 = new StringBuilder();
   sb1.append("--");
   sb1.append(BOUNDARY);
   sb1.append("\r\n");
   sb1.append(new StringBuilder()
     .append("Content-Disposition: form-data; name=\"")
     .append("file").append("\"; filename=\"")
     .append(file.getName()).append("\"")
     .append("\r\n").toString());
   sb1.append("Content-Type: application/octet-stream; charset=UTF-8\r\n");
   sb1.append("\r\n");
   outStream.write(sb1.toString().getBytes());
   outStream.flush();
   
   FileInputStream in = new FileInputStream(file); //获得文件输入流
         byte[] fileBytes = new byte[(int)file.length()];
   in.read(fileBytes);
        
   byte[] filebytes = fileBytes;
   outStream.write(filebytes, 0, filebytes.length);
   outStream.flush();
   outStream.write("\r\n".getBytes());
   outStream.flush();

   byte[] endData = new StringBuilder().append("--").append(BOUNDARY)
     .append("--").append("\r\n").toString().getBytes();
   outStream.write(endData);
   outStream.flush();
   outStream.close();

   int responseCode = conn.getResponseCode();

   if (responseCode != 200) {
    BufferedReader reader = new BufferedReader(new InputStreamReader(
      conn.getErrorStream()));
    String line = null;
    StringBuffer errorMsg = new StringBuffer();
    if ((line = reader.readLine()) != null) {
     errorMsg.append(line).append("\n");
    }
    reader.close();

    throw new IOException(errorMsg.toString());
   }
   

   BufferedReader reader = new BufferedReader(new InputStreamReader(
     conn.getInputStream(), "utf-8"));
   String line = "";
   while ((line = reader.readLine()) != null) {
    buffer.append(line);
   }
   reader.close();

  } catch (MalformedURLException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
   return "false";
  } catch (ProtocolException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
   return "false";
  } catch (UnsupportedEncodingException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
   return "false";
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
   return "false";
  }

  if (conn != null) {
   conn.disconnect();
  }
  
  return buffer.toString();
 }

 

//调用方法

File file = new File("e:\\1.3gp");
  Map<String,String> paramMap = new HashMap<String,String>();
  Map<String,String> map = new HashMap<String,String>();
  map.put("type", "video");
  map.put("name","file");
  
  
  String uploadBack=Test.postUrlWithData(uploadRequest.getUploadUrl(), paramMap,file, map);

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值