没有根的野草,漂浮的命途

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

Java模拟表单POST跨域访问

publicclass Test {

 

 

public static void main(String[] args) throws IOException {

 

 

String filepath="pro.jpg";

HttpClient hc = new HttpClient();

hc.getHostConfiguration().setHost("file.myhrbanlv.com", 80, "http");

 

//读取本地图片

InputStream resStream = new FileInputStream(filepath);

BufferedReader br = new BufferedReader(new InputStreamReader(resStream));

StringBuffer resBuffer = new StringBuffer();

String resTemp = "";

while ((resTemp = br.readLine()) != null) {

resBuffer.append(resTemp);

}

String result = resBuffer.toString();

System.out.println(result);

 

 

//String targetURL="/index.php/public?uid=24&uname=test23&mysite=''&rand="+Math.random();

String targetURL="/index.php";

PostMethod pm = new PostMethod(targetURL);

File pic=new File("hello.jpg");

File target = new File(filepath);

try {

FileUtils.copyFile(target, pic);

} catch (Exception e) {

}

// 通过以下方法可以模拟页面参数提交

// filePost.setParameter("name", "中文");

 

List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);

//Your DATA

 

  nameValuePairs.add(new NameValuePair("action", "publish"));

  nameValuePairs.add(new NameValuePair("uid", "24"));

  nameValuePairs.add(new NameValuePair("uname", "test23"));

  nameValuePairs.add(new NameValuePair("mysite", ""));

  nameValuePairs.add(new NameValuePair("rand","'"+ Math.random()+"'"));

//   pm.setRequestBody(nameValuePairs.toArray(new NameValuePair[nameValuePairs.size()]));

//pm.setParameter("action", "publish");

//pm.setParameter("uid", "24");

//pm.setParameter("uname", "test23");

//pm.setParameter("mysite", "");

//pm.setParameter("rand","'"+ Math.random()+"'");

 

System.out.println(pm.getParameters().toString());

 

Part[] parts = { new FilePart("publisher_file", pic) ,new StringPart("action", "publish"),new StringPart("uid", "24"),new StringPart("uname", "test23"),new StringPart("mysite", ""),new StringPart("rand","'"+ Math.random()+"'")};

pm.setRequestEntity(new MultipartRequestEntity(parts, pm.getParams()));

//hc.getHttpConnectionManager().getParams().setConnectionTimeout(5000);

int status = hc.executeMethod(pm);

System.out.println(status+""+(status == HttpStatus.SC_OK));

 

try

    BufferedReader rd = new BufferedReader(new InputStreamReader( 

            pm.getResponseBodyAsStream(), "GBK")); 

    StringBuffer stringBuffer = new StringBuffer(); 

    String line; 

    while ((line = rd.readLine()) != null) { 

        stringBuffer .append(line); 

    } 

    rd.close(); 

    System.out.println("接受到的流是:" + stringBuffer + "—-" + status); 

} catch (Exception e) { 

    throw new RuntimeException("error",e);

}

 

}

}

posted on 2012-05-09 11:21  针尖上的舞者  阅读(1068)  评论(0)    收藏  举报