java執行http請求亂碼解決
阿新 • • 發佈:2019-01-05
痛過java進行http請求會出現亂碼解決方式:
URLEncoder.encode(String s, String enc) //引數
使用指定的編碼機制將字串轉換為 application/x-www-form-urlencoded 格式
URLDecoder.decode(String s, String enc)
使用指定的編碼機制對 application/x-www-form-urlencoded 字串解碼。
傳送的時候使用URLEncoder.encode編碼,接收的時候使用URLDecoder.decode解碼,都按指定的編碼格式進行編碼、解碼,可以保證不會出現亂碼
String url = "http://localhost/users/update?user_id="+ id +"&user_name="+URLEncoder.encode(changeName, "UTF-8");
String result = httpURLConnection.post(url, headers, "");
public String post(String url, Map<String, String> headers, String postData) throws Exception { BufferedReader in = null; HttpURLConnection conn = null; try { StringBuffer result = new StringBuffer(); URL realUrl = new URL(url); conn = (HttpURLConnection) realUrl.openConnection(); if(headers != null) { for(Map.Entry<String, String> header : headers.entrySet()) { conn.setRequestProperty(header.getKey(),header.getValue()); } } // 設定通用的請求屬性 conn.setRequestMethod("POST"); conn.setRequestProperty("Accept", "*/*"); //conn.setRequestProperty("Accept-Encoding", "gzip"); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); conn.setDoOutput(true); conn.setDoInput(true); // Post 請求不能使用快取 conn.setUseCaches(false); conn.setConnectTimeout(3000); conn.setReadTimeout(5000); if(!StringUtils.isBlank(postData)) { OutputStream out = conn.getOutputStream(); out.write(postData.getBytes("utf-8")); out.flush(); out.close(); } in = new BufferedReader( new InputStreamReader(conn.getInputStream(), "utf-8")); String line = ""; while ((line = in.readLine()) != null) { result.append(line); } return result.toString(); }catch(Exception e) { throw e; }finally { if (in != null) { in.close(); } } }
@Override public String get(String url, Map<String, String> headers) throws Exception { HttpURLConnection conn = null; BufferedReader bufReader = null; InputStream in = null; try { StringBuilder sb = new StringBuilder(); conn = (HttpURLConnection) new URL(url).openConnection(); conn.setDoInput(true); conn.setDoOutput(true); if(headers != null) { for(Map.Entry<String, String> header : headers.entrySet()) { conn.setRequestProperty(header.getKey(),header.getValue()); } } //conn.setRequestProperty("Accept-Encoding", "gzip"); conn.setConnectTimeout(4000); conn.setReadTimeout(120000); in = conn.getInputStream(); // int status = conn.getResponseCode(); // if(conn.getRequestProperty("Accept-Encoding").contains("gzip")) { // if(in != null) // in = new GZIPInputStream(in); // } bufReader = new BufferedReader(new InputStreamReader(in, "utf-8")); String newsContents = ""; while ((newsContents = bufReader.readLine()) != null) { sb.append(newsContents); } return sb.toString(); }catch(Exception e) { throw e; }finally { if(bufReader != null) bufReader.close(); if(in != null) in.close(); } }