HTTP request garbled solution one
This is also the simplest way, mainly using the IOUtils
tool class.
URL realUrl = new URL(url); // 打开和URL之间的连接 conn = (HttpURLConnection) realUrl.openConnection(); // 发送POST请求必须设置如下两行 conn.setRequestMethod(StringUtils.upperCase(type));// 提交模式 conn.setDoInput(true); conn.setDoOutput(true); conn.setUseCaches(false); conn.setRequestProperty("Connection", "close"); conn.setConnectTimeout(3000); //设置连接主机超时(单位:毫秒) conn.setReadTimeout(2000); //设置从主机读取数据超时(单位:毫秒) //省略一些代码 //获取InputStream InputStream inStream = conn.getInputStream(); //通过IOUtils 转化,把流转换为字符串。 //charset为编码格式,可选为"utf-8","gbk","gb2312"等等 String result = IOUtils.toString(inStream,charset);
Recommended online video tutorial: java course
HTTP request garbled solution two
Next, use the above code, use our most commonly used method, read line by line, the charset is the same as above.
StringBuffer sb = new StringBuffer(""); in = new BufferedReader(new InputStreamReader(inStream, charset)); String line = ""; while ((line = in.readLine()) != null){ sb.append(line); } result = sb.toString();
If you want to know more about java, please visit: Introduction to java language
The above is the detailed content of How to solve garbled http request in java. For more information, please follow other related articles on the PHP Chinese website!