失眠网,内容丰富有趣,生活中的好帮手!
失眠网 > java调用 restapi 乱码_Java HttpURLConnection模拟请求Rest接口解决中文乱码问题

java调用 restapi 乱码_Java HttpURLConnection模拟请求Rest接口解决中文乱码问题

时间:2021-11-26 07:31:01

相关推荐

java调用 restapi 乱码_Java HttpURLConnection模拟请求Rest接口解决中文乱码问题

public staticString PostRequest(String URL,String obj) {

String jsonString="";try{//创建连接

URL url = newURL(URL);

HttpURLConnection connection=(HttpURLConnection) url

.openConnection();

connection.setDoOutput(true);

connection.setDoInput(true);

connection.setRequestMethod("POST"); //设置请求方法

connection.setRequestProperty("Charsert", "UTF-8"); //设置请求编码

connection.setUseCaches(false);

connection.setInstanceFollowRedirects(true);

connection.setRequestProperty("Content-Type","application/json");

connection.connect();//POST请求

DataOutputStream out = newDataOutputStream(

connection.getOutputStream());//关键的一步

out.writeBytes(obj);

out.flush();

out.close();//读取响应

if (connection.getResponseCode()==200) {

BufferedReader reader= new BufferedReader(newInputStreamReader(connection.getInputStream()));

String lines;

StringBuffer sb= new StringBuffer("");while ((lines = reader.readLine()) != null) {

lines= new String(lines.getBytes(), "utf-8");

sb.append(lines);

}

jsonString=sb.toString();

reader.close();

}//返回值为200输出正确的响应信息

if (connection.getResponseCode()==400) {

BufferedReader reader= new BufferedReader(newInputStreamReader(connection.getErrorStream()));

String lines;

StringBuffer sb= new StringBuffer("");while ((lines = reader.readLine()) != null) {

lines= new String(lines.getBytes(), "utf-8");

sb.append(lines);

}

jsonString=sb.toString();

reader.close();

}//返回值错误,输出错误的返回信息//断开连接

connection.disconnect();

}catch(MalformedURLException e) {//TODO Auto-generated catch block

e.printStackTrace();

}catch(UnsupportedEncodingException e) {//TODO Auto-generated catch block

e.printStackTrace();

}catch(IOException e) {//TODO Auto-generated catch block

e.printStackTrace();

}returnjsonString;

}

如果觉得《java调用 restapi 乱码_Java HttpURLConnection模拟请求Rest接口解决中文乱码问题》对你有帮助,请点赞、收藏,并留下你的观点哦!

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。