使用URLConnection发送和检索地图

时间:2017-09-01 10:03:32

标签: java

我想将Swing应用程序中的HashMap发送到Web Application.HashMap类型是。它包含One String,ArrayList和Byte Array。我想在Web应用程序中检索此Map。

Swing Side Code:

private static void sendMap()
    {
        System.out.println("Sending MAP");
        byte[] bytes=getByteArray();
        ArrayList<String> list =new ArrayList<String>();
        list.add("ABC");
        list.add("XYZ");
        list.add("ABXY");
        Map<String, Object> params=new HashMap<String, Object>();
        params.put("Type", "Document");
        params.put("bytes", bytes);
        params.put("PartyNameList", list);

        try {
            URL url=  new URL(iinkiturl+"/getMap?id=1234567");
            URLConnection uc = url.openConnection();
            uc.setDoOutput(true);
            uc.setDoInput(true);
            uc.setAllowUserInteraction(false);

            DataOutputStream dstream = new DataOutputStream(uc.getOutputStream());

            // The POST line
            System.out.println(toByteArray(params));
            dstream.write(params.toString().getBytes());
            dstream.close();

             InputStream in = uc.getInputStream();
            int x;
            while ((x = in.read()) != -1) {
                System.out.write(x);
            }
            in.close();

            BufferedReader r = new BufferedReader(new InputStreamReader(in));
            StringBuffer buf = new StringBuffer();
            String line;
            while ((line = r.readLine()) != null) {
                buf.append(line);
            }


        } catch(Exception exception)
        {
            exception.printStackTrace();
        }


    }

Web应用程序端:

        InputStream in = request.getInputStream();
        BufferedReader r = new BufferedReader(new InputStreamReader(in));
        StringBuffer buf = new StringBuffer();
        String line;
        while ((line = r.readLine())!=null) {
        buf.append(line);
        } 
        System.out.println("Buffer ======= "+buf.toString());

输出:

缓冲区======= {Type = Filing,PartyNameList = [ABC,XYZ,ABXY],bytes = [B @ 24c0f1ec}

如何从此Buffer获取Map对象。或者是否有任何替代解决方案来实现这一点。在此先感谢。

3 个答案:

答案 0 :(得分:1)

您只使用toString()方法。它不可能从中进行反序列化。 使用JSON或Java序列化工具将Map移动到可转移状态(视图)。客户端使用相同的工具对其进行反序列化。

答案 1 :(得分:0)

在您的情况下使用toString()生成HashMap的字符串表示形式,并通过网络发送它而不是实际的HashMap,这就是您在Web应用程序端看到该表示的原因。

您应该使用ObjectOutputStream/ObjectInputStream课程来发送/接收 HashMap

ObjectOutputStream/ObjectInputStream特别关注通过网络发送Object。

但是,这需要您要通过的所有对象发送 network(此过程称为序列化)必须实现Serializable接口,这是一个标记接口。

答案 2 :(得分:0)

我的问题是使用JSON解决的。

Swing Side Code:

<?php
/**
 * Tutorial: PHP Login Registration system
 *
 * Page : Profile
 */

// Start Session
session_start();

// check user login
if(empty($_SESSION['user_id']))
{
    header("Location: index.php");
}

// Database connection
require __DIR__ . '/database.php';
$db = DB();

// Application library ( with DemoLib class )
require __DIR__ . '/lib/library.php';
$app = new DemoLib();


$user = $app->UserDetails($_SESSION['user_id']); // get user details
$ident = $user->user_id;






if(isset($_POST["submit"])){
$hostname='localhost';
$username='root';
$password='';

try {
$dbh = new PDO("mysql:host=$hostname;dbname=college",$username,$password);

$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // <== add this line
$sql = "INSERT INTO students (user_id,full_name, gender, dob, present_add, contact_add, interest, qualification, course_date, board_name, marks, phone)
VALUES ('".$_POST[$ident]."', '".$_POST["full_name"]."', '".$_POST["gender"]."', '".$_POST["dob"]."', '".$_POST["present_add"]."', '".$_POST["contact_add"]."', '".$_POST["interest"]."', '".$_POST["qualification"]."' ,'".$_POST["course_date"]."','".$_POST["board_name"]."', '".$_POST["marks"]."', '".$_POST["phone"]."')";
if ($dbh->query($sql)) {
echo "<script type= 'text/javascript'>alert('New Record Inserted Successfully');</script>";
}
else{
echo "<script type= 'text/javascript'>alert('Data not successfully Inserted.');</script>";
}

$dbh = null;
}
catch(PDOException $e)
{
echo $e->getMessage();
}

}
?>
<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Profile</title>
    <!-- Latest compiled and minified CSS -->
    <link rel="stylesheet" href="css/bootstrap.min.css">
</head>
<body>
    <div class="container">
        <div class="well">
            <h2>
                Profile
            </h2>
            <h3>Hello <?php echo $ident ?>,</h3>
            <p>
                Lorem ipsum dolor sit amet, consectetur adipisicing elit. Consectetur deserunt dolore fuga labore magni maxime, quaerat reiciendis tenetur? Accusantium blanditiis doloribus earum error inventore laudantium nesciunt quis reprehenderit ullam vel?
            </p>
            <a href="logout.php" class="btn btn-primary">Logout</a>
        </div>





<form action="" method="post">
<label>Full Name :</label>
<input type="text" name="full_name" id="full_name" required="required" placeholder="First Middle Last"/><br /><br />
<label>Gender</label>  
  <input type="radio" name="gender" id="gender" value="male" checked> Male<br>
  <input type="radio" name="gender" id="gender" value="female"> Female<br>
  <input type="radio" name="gender" id="gender" value="other"> Other<br /><br />
<label>Date Of Birth :</label>
<input type="date" name="dob" id="dob" required="required" placeholder="yyyy-mm-dd"/><br /><br />
<label>Present Address :</label>
<input type="text" name="present_add" id="present_add" required="required" placeholder="Enter Your Present Address"/><br /><br />
<label>Contact Address :</label>
<input type="text" name="contact_add" id="contact_add" required="required" placeholder="Enter Your Contact Address"/><br /><br />
<label>Programme you Wish to Apply for :</label>
  <select name="interest" id="interest">
    <option value="B.tech">B.tech</option>
    <option value="MBBS">MBBS</option>
    <option value="B.Arch">B.Arch</option>
    <option value="B.Pharm">B.Pharm</option>
    <option value="B.A">B.A</option>
    <option value="B.Sc">B.Sc</option>
    <option value="M.Pharm">M.Pharm</option>
    <option value="M.tech">M.tech</option>
    <option value="M.A">M.A</option>
    <option value="MBA">MBA</option>
    <option value="M.Sc">M.Sc</option>
  </select><br /><br />
<label>Name of Secondary School/High School/College/University :</label>
<input type="text" name="qualification" id="qualification" required="required" placeholder="Please Enter The Relevant Exam Name You Recently Appeared For"/><br /><br />
<label>Dates Attended From and To :</label>
<input type="text" name="course_date" id="course_date" required="required" placeholder="yyyy-mm-dd to yyyy-mm-dd"/><br /><br />
<label>Board Name :</label>
<input type="text" name="board_name" id="board_name" required="required" placeholder="Name of Board"/><br /><br />
<label>Marks :</label>
<input type="text" name="marks" id="marks" required="required" placeholder="Grades Achieved"/><br/><br />
<label>phone :</label>
<input type="text" name="phone" id="phone" required="required" placeholder="Please Enter your Phone Number"/><br /><br />
<input type="submit" value=" Submit " name="submit"/><br />
</form>



</div>
<?php

?>      
</body>
</html>

Web应用程序端:

private static void sendMap()
    {
        System.out.println("Sending MAP");
        ArrayList<String> list =new ArrayList<String>();
        list.add("ABC");
        list.add("XYZ");
        list.add("ABXY");
        Map<String, Object> params=new HashMap<String, Object>();
        params.put("Type", "Document");
        params.put("bytes", getByteArray());
        params.put("NameList", list);

        try {
            URL url=  new URL(iinkiturl+"/getMap?id=1234567");
            URLConnection uc = url.openConnection();
            uc.setDoOutput(true);
            uc.setDoInput(true);
            uc.setAllowUserInteraction(false);

            DataOutputStream dstream = new DataOutputStream(uc.getOutputStream());

            dstream.write(new com.google.gson.Gson().toJson(params).getBytes());
            dstream.close();

             InputStream in = uc.getInputStream();
            int x;
            while ((x = in.read()) != -1) {
                System.out.write(x);
            }
            in.close();

            BufferedReader r = new BufferedReader(new InputStreamReader(in));
            StringBuffer buf = new StringBuffer();
            String line;
            while ((line = r.readLine()) != null) {
                buf.append(line);
            }


        } catch(Exception exception)
        {
            exception.printStackTrace();
        }


    }