JAVA跨域数据提交

1、上传文件

(1)、图片

public void postFile(String imgpath,String fileuuid) throws Exception{
String response="";
Properties pro = GetProperties.getKey("wgh.properties");
String fileurl = pro.getProperty("fileUrl");
PostMethod postMethod = new PostMethod(fileurl);
HttpClient client = new HttpClient();
String resource =  this.getClass().getClassLoader().getResource("").getPath();
resource = resource.substring(1, resource.indexOf("WEB-INF/")); 
String imgfile = resource+imgpath;
File file = new File(imgfile);
if(file.exists()){
FilePart fp = new FilePart("file",file);
fp.setCharSet("utf-8");                     //格式
fp.setContentType("image/*");//类型


//StringPart:普通文本参数
StringPart idPart = new StringPart("fileuuid",fileuuid);
Part[] parts = {idPart,fp};


//HttpClient使用MultipartRequestEntity包装
MultipartRequestEntity mre = new MultipartRequestEntity(parts,postMethod.getParams());
postMethod.setRequestEntity(mre);


//由于要上传的文件可能比较大,因此在此设置最大的连接超时时间
client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
int status = client.executeMethod(postMethod);
if(status ==HttpStatus.SC_OK){
InputStream inputStream = postMethod.getResponseBodyAsStream();
BufferedReader br = new  BufferedReader(new InputStreamReader(inputStream));
StringBuffer stringBuffer =new StringBuffer();
String str ="";
while ((str = br.readLine())!=null){
stringBuffer.append(str);
}
response = stringBuffer.toString();
}else{
response = "fail";
}
System.out.println("图片同步结果:"+response);
}
}

(2)、文件

 public static String doUploadFile(File file, String url) throws IOException {
        String response = "";
        if (!file.exists()) {
            return "file not exists";
        }
        PostMethod postMethod = new PostMethod(url);
        try {
            //----------------------------------------------
            // FilePart:用来上传文件的类,file即要上传的文件
            FilePart fp = new FilePart("file", file);
            Part[] parts = { fp };

            // 对于MIME类型的请求,httpclient建议全用MulitPartRequestEntity进行包装
            MultipartRequestEntity mre = new MultipartRequestEntity(parts,
                    postMethod.getParams());
            postMethod.setRequestEntity(mre);
            //---------------------------------------------
            HttpClient client = new HttpClient();
            client.getHttpConnectionManager().getParams()
                    .setConnectionTimeout(50000);// 由于要上传的文件可能比较大 , 因此在此设置最大的连接超时时间
            int status = client.executeMethod(postMethod);
            if (status == HttpStatus.SC_OK) {
                InputStream inputStream = postMethod.getResponseBodyAsStream();
                BufferedReader br = new BufferedReader(new InputStreamReader(
                        inputStream));
                StringBuffer stringBuffer = new StringBuffer();
                String str = "";
                while ((str = br.readLine()) != null) {
                    stringBuffer.append(str);
                }
                response = stringBuffer.toString();
            } else {
                response = "fail";
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 释放连接
            postMethod.releaseConnection();
        }
        return response;
    }


2、提交数据

(1)、向指定 URL 发送POST方法的请求

public PageData  commitDisclose(PageData pd) throws Exception {
PageData pdc = new PageData();
pdc.put("id", pd.getString("id"));
NameValuePair[] params = {
new NameValuePair("name" , pd.getString("name")),
        new NameValuePair("caseTitle" , pd.getString("title")),
               new NameValuePair("caseDesc" , pd.getString("content")),
               new NameValuePair("locationDesc" , pd.getString("address")),
               new NameValuePair("coordLat" , pd.getString("latitude")),
               new NameValuePair("coordLong" , pd.getString("longitude")),
               new NameValuePair("streetDepartId" , pd.getString("streetDepartId")),
               new NameValuePair("streetName" , pd.getString("streetName")),
               new NameValuePair("communityDepartId" , pd.getString("communityDepartId")),
               new NameValuePair("communityName" , pd.getString("communityName")),
               new NameValuePair("gridId" , pd.getString("gridId")),
               new NameValuePair("gridName" , pd.getString("gridName")),
               new NameValuePair("tag" , "weixin"),//类型
               new NameValuePair("caseOrigin" , "2"),     //案件来源
               new NameValuePair("overStatus" , "0")    
               };
Properties pro = GetProperties.getKey("wgh.properties");
String host = pro.getProperty("host");
String port = pro.getProperty("port");
String url = pro.getProperty("reportUrl");
JSONObject result;
try {
result = HttpRequest.sendPost(host , port, url, params);
pdc.put("eId", result.getJSONObject("object").get("id"));   //返回的案件编码
pdc.put("isSynchro", "1");   //是否同步 0是否 1是是
pdc.put("isDo", "0");//处理状态  0已上报
dao.update("ReportMapper.edit", pdc);
System.out.println("数据同步平台成功");
} catch (Exception e) {
e.printStackTrace();
System.out.println("数据同步平台失败");
}
return pdc;
}


 public static JSONObject sendPost( String host,String port,String requestUrl, NameValuePair[] params){
    JSONObject jsonObject = null;
    String buffer = null;
    HttpClient httpClient = new HttpClient();
   
        //httpClient.getHostConfiguration().setHost(host, 8080, "http"); 

HttpMethod method = postMethod(requestUrl,params);
        try {
httpClient.executeMethod(method);
buffer = method.getResponseBodyAsString();
} catch (IOException e) {
 System.out.println("-------------------发送post请求出现异常!-----------------------------------");
//e.printStackTrace();
}

 //释放连接  
     method.releaseConnection(); 

jsonObject = JSONObject.fromObject(buffer);
return jsonObject;
    }


private static HttpMethod postMethod(String url,NameValuePair[] param) throws IOException{
       PostMethod post = new PostMethod(url);
       post.setRequestHeader("Content-Type","application/x-www-form-urlencoded;charset=UTF-8"); 
       post.setRequestBody(param);
       post.releaseConnection();
       return post;
   }


(2)、向指定的url发送get请求

String result =  HttpRequest.sendGet(url + pds.getString("eId"));


public static String sendGet(String url) {
        String result = "";
        BufferedReader in = null;
        try {
            String urlNameString = url;
            URL realUrl = new URL(urlNameString);
            // 打开和URL之间的连接
            URLConnection connection = realUrl.openConnection();
            // 设置通用的请求属性
            connection.setRequestProperty("accept", "*/*");  
            connection.setRequestProperty("connection", "Keep-Alive");  
            connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
            // 建立实际连接
            connection.connect();
            // 获取所有响应头字段
            Map<String, List<String>> map = connection.getHeaderFields();  
            // 定义 BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(connection.getInputStream(),"utf-8"));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("----------------------发送GET请求出现异常!-------------------------");
           // e.printStackTrace();
        }
        // 使用finally块来关闭输入流
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
              //  e2.printStackTrace();
            }
        }
        return result;
    }

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值