0

当我传递一个 url 时,我有一个关于 URI 和 URL 的问题,效果很好,但结果最糟糕,需要帮助!

因为我的代码看起来像这样。

import java.io.*;
import java.net.*;
import java.net.URL;

public class isms {
    public static void main(String[] args) throws Exception {
        try {


       String user = new String ("boo");
       String pass = new String ("boo");
       String dstno = new String("60164038811"); //You are going compose a message to this destination number.
       String msg = new String("你的哈达哈达!"); //Your message over here
       int type = 2; //for unicode change to 2, normal will the 1.
       String sendid = new String("isms"); //Malaysia does not support sender id yet.

            // Send data
            URI myUrl = new URI("http://www.isms.com.my/isms_send.php?un=" + user + "&pwd=" + pass 
                + "&dstno=" + dstno + "&msg=" + msg + "&type=" + type + "&sendid=" + sendid);
            URL url = new URL(myUrl.toASCIIString());

            URLConnection conn = url.openConnection();
            conn.setDoOutput(true);

            // Get the response
            BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = rd.readLine()) != null) {
                // Print the response output...
                System.out.println(line);
            }      
            rd.close();

            System.out.println(url);
        } catch (Exception e) {
            e.printStackTrace();
        }



    }
}

web中的输出不同..我的java输出是

你的哈达哈达!

但在我的网站上是

ÄãµÄ¹þ´ï¹þ´ï!

帮助!!

4

1 回答 1

0
String user = new String ("boo");

在 Java 中你不需要(也不应该)这样做new String——<code>String user = "boo"; 很好。

String msg = new String("你的哈达哈达!");

在源代码中写入非 ASCII 字符意味着您必须获取-encoding标志javac以匹配您保存文本文件的编码。您可能已将 .java 文件保存为 UTF-8,但未将构建环境配置为在编译时使用 UTF-8。

如果您不确定自己是否正确,则可以同时使用 ASCII 安全\u转义:

String msg = "\u4F60\u7684\u54C8\u8FBE\u54C8\u8FBE!";  // 你的哈达哈达!

最后:

URI myUrl = new URI("http://www.isms.com.my/isms_send.php?un=" + user + "&pwd=" + pass 
            + "&dstno=" + dstno + "&msg=" + msg + "&type=" + type + "&sendid=" + sendid);

当您将 URI 放在一起时,您应该对字符串中包含的每个参数进行 URL 转义。否则&,值中的任何或其他无效字符都会破坏查询。这也允许您选择用于创建查询字符串的字符集。

String enc = "UTF-8";
URI myUrl = new URI("http://www.isms.com.my/isms_send.php?" +
    "un=" + URLEncoder.encode(user, enc) +
    "&pwd=" + URLEncoder.encode(pass, enc) +
    "&dstno=" + URLEncoder.encode(dstno, enc) +
    "&msg=" + URLEncoder.encode(msg, enc) +
    "&type=" + URLEncoder.encode(Integer.toString(type), enc) +
    "&sendid=" + URLEncoder.encode(sendid, enc)
);

正确的值enc取决于您连接的服务,但这UTF-8是一个很好的猜测。

于 2013-07-09T14:59:56.770 回答