Monday, May 14, 2018

Java: sendGet request時亂碼問題

InputStreamReader沒有加入UTF-8,導致發在tomcat server中錯誤分析回傳的內容的編碼。


======================= URLConnection.java ======================
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map.Entry;

import org.json.JSONObject;

public class URLConnection {
private final String USER_AGENT = "Mozilla/5.0";

// HTTP GET request
public JSONObject sendGet(String input_url, HashMap<String, String> parameter_map) throws Exception {
String parameter_string = "";
Iterator<Entry<String, String>> it = parameter_map.entrySet().iterator();
while (it.hasNext()){
Entry<String, String> pair = it.next();
parameter_string += "?" + URLEncoder.encode(pair.getKey(), "UTF-8") + "=" + URLEncoder.encode(pair.getValue(), "UTF-8");
}

String url = input_url + parameter_string;

URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();

// optional default is GET
con.setRequestMethod("GET");

//add request header
con.setRequestProperty("User-Agent", USER_AGENT);

int responseCode = con.getResponseCode();
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8"));
String inputLine;
StringBuffer response = new StringBuffer();

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

//print result
JSONObject responseJson = new JSONObject(response.toString());
return responseJson;
}
}

No comments: