java执行http请求乱码解决

痛过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 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 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 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 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();
		}
	}



你可能感兴趣的:(JAVA技术)