【JAVA】文件读取编码判断和调用第三方接口

判断文件编码可以防止乱码问题。
方法为:

//判断是否为gbk编码,返回true或false
java.nio.charset.Charset.forName("gbk").newEncoder().canEncode(filePath)

调用第三方提供的接口:

	//serverURL  目标接口地址
	URL url = new URL(serverURL);
	HttpURLConnection connection = (HttpURLConnection) url.openConnection();
	connection.setRequestMethod("POST");//请求方式
	connection.setDoInput(true);//用于post请求
	connection.setDoOutput(true);//用于post请求
	//请求头参数
	connection.setRequestProperty("Content-Type", "application/json");
	connection.setRequestProperty("Charset", "utf-8");
	connection.setRequestProperty("param1", x1);
	connection.setRequestProperty("param2", x2);
	connection.setRequestProperty("param3", x3);
	connection.connect();
	OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream(), "UTF-8");
	//body参数
	JSONObject parm = new JSONObject();
	parm.put("body1", b1);
	parm.put("body2", "b2");
	parm.put("body3", "");
	writer.write(parm.toString());
	writer.flush();
	//返回值
	InputStream is = connection.getInputStream();
	BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
	while ((strRead = reader.readLine()) != null) {
		sbf.append(strRead);
	}
	reader.close();
	connection.disconnect();
	String results = sbf.toString();
	JSONObject resultJson = new JSONObject(results);

你可能感兴趣的:(经验累积,java,开发语言,servlet)