日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 >

java restful中文乱码_restful服务接口访问乱码 和 505错误

發布時間:2024/9/27 34 豆豆
生活随笔 收集整理的這篇文章主要介紹了 java restful中文乱码_restful服务接口访问乱码 和 505错误 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

標簽:

用cxf 發部個rest服務,用瀏覽器訪問和 HttpURLConnection 訪問。

1. URL中有中文,瀏覽器訪問正常,HttpURLConnection 失敗。

解決: HttpURLConnection 方式需要做兼容處理。

queryParam 傳入參數,服務實現方法中要處理,如果是亂碼要轉換,如果中文直接查詢

if (!isChineseChar(queryParam))

{

queryParam = new String(queryParam.getBytes("iso8859-1"), "utf-8");

}

// 判斷中文

public static boolean isChineseChar(String str)

{

boolean temp = false;

Pattern p=Pattern.compile("[\u4e00-\u9fa5]");

Matcher m=p.matcher(str);

if(m.find()){

temp =? true;

}

return temp;

}

2. HttpURLConnection 請求中 參數中如果有? 空格,請求則會 505錯誤

解決: 需要對有空格的參數 做URL編碼處理。import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStreamReader;

import java.net.MalformedURLException;

import java.net.URL;

import java.net.URLEncoder;

import sun.net.www.protocol.http.HttpURLConnection;

import com.alibaba.fastjson.JSONObject;

public class SingleTableRestClient

{

private static final String targetURL = "http://localhost:8080/agd-restful/services/restful/QueryService/queryData/*?queryParam=";

public static void main(String[] args)

{

JSONObject obj = new JSONObject();

obj.put("XM", "匡匡");

obj.put("BIRTHDAY", getURLEncoder("1988-01-01 00:00:00,1988-12-30 00:00:00"));

String urls = targetURL + obj.toString();

requestRestServer(urls);

}

public static JSONObject requestRestServer(String url)

{

JSONObject obj = new JSONObject();

try

{

URL restServiceURL = new URL(url);

HttpURLConnection httpConnection = (HttpURLConnection) restServiceURL.openConnection();

httpConnection.setRequestMethod("GET");

httpConnection.setRequestProperty("Accept", "application/json");

httpConnection.setRequestProperty("Accept-Charset", "UTF-8");

httpConnection.setRequestProperty("contentType", "UTF-8");

if (httpConnection.getResponseCode() != 200) {

throw new RuntimeException("HTTP GET Request Failed with Error code : "

+ httpConnection.getResponseCode());

}

BufferedReader responseBuffer = new BufferedReader(new InputStreamReader(

(httpConnection.getInputStream()),"utf-8"));

String output = "";

String result = "";

System.out.println("Output from Server:? \n");

while ((output = responseBuffer.readLine()) != null) {

//System.out.println(output);

result = output;

}

obj = JSONObject.parseObject(result);

System.out.println(obj.toString());

httpConnection.disconnect();

} catch (MalformedURLException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

}

return obj;

}

@SuppressWarnings("deprecation")

private static String getURLEncoder(String dest)

{

return URLEncoder.encode(dest);

}

}修改后? 正常ok

標簽:

總結

以上是生活随笔為你收集整理的java restful中文乱码_restful服务接口访问乱码 和 505错误的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。