通过HTTP帖子发送阿拉伯语作为参数不起作用

时间:2016-09-27 18:09:04

标签: java httprequest httpurlconnection

我点击了一个带有阿拉伯语参数值的网址(如下所示):

http://62.215.226.164/fccsms_P.aspx?UID=something&P=somethingS=InfoText&G=96567771404&M=اخص شقث غخع خن ؤخةث&L=E

完美无缺;我用阿拉伯语在手机上收到消息。但是,当我尝试通过以下代码实现相同时,我只在消息中得到问号。

public void sendSms(SendSms object) 
    throws MalformedURLException, ProtocolException, IOException
{
    String message = new String(object.getMessage().getBytes(), "UTF-8");
    System.out.println(message); // This also prints only question marks
    PrintStream out = new PrintStream(System.out, true, "UTF-8");
    out.print(message);

    String charset="UTF-8";

    URL url = new URL("http://62.215.226.164/fccsms_P.aspx");
    HttpURLConnection con = (HttpURLConnection) url.openConnection();
    con.setRequestProperty("Accept-Charset", charset);

    con.setRequestMethod("POST");

    // con.setRequestProperty("User-Agent", USER_AGENT);
    con.setRequestProperty("Accept-Language", "en-US,en,ar_KW;q=0.5");
    con.setRequestProperty("Content-Type", "text/html;charset=utf-8");
    String urlParameters = "UID=test&P=test&S=InfoText&G=965" + object.getPhone() + "&M= Hello " + object.getName() + " " + message + " &L=A";

    // Send post request
    con.setDoOutput(true);
    DataOutputStream wr = new DataOutputStream(con.getOutputStream());
    wr.writeBytes(urlParameters);
    wr.flush();
    wr.close();

    int responseCode = con.getResponseCode();
    System.out.println("\nSending 'POST' request to URL : " + url);
    System.out.println("Post parameters : " + urlParameters);
    System.out.println("Response Code : " + responseCode);

    BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
    String inputLine;
    StringBuffer response = new StringBuffer();

    while ((inputLine = in.readLine()) != null) {
        response.append(inputLine);
    }

    in.close();
 }

要使用阿拉伯语获取消息,我需要在代码中添加或更改哪些内容?

2 个答案:

答案 0 :(得分:0)

如果要将阿拉伯数据作为参数发送,则需要将此数据编码为UTF-8。

您可以使用以下代码来获得正确的输出。

  BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(conn.getOutputStream(), "UTF-8"));
  bw.write(urlParameters);
  bw.flush();
  bw.close();

以下代码中出现问题。所以用上面的代码替换下面的代码。

  DataOutputStream wr = new DataOutputStream(con.getOutputStream());
  wr.writeBytes(urlParameters);
  wr.flush();
  wr.close();

答案 1 :(得分:-1)

这是因为http不支持字符集, 您的浏览器会自动处理网址编码, 在您的代码中,您需要单独编码每个参数,因为特殊字符,例如。 asuming object.getMessage()不返回???:

public MyUserControl()
{
    InitializeComponent();

    Customer cust = (Customer)this.DataContext;
    // cust is null????
}

然后连接:

String message = URLEncoder.encode(
""اخص شقث غخع خن ؤخةث",
java.nio.charset.StandardCharsets.UTF_8.toString() );