GET、POST请求处理中文问题(用HttpURLConnection模拟发送请求)
一、首先是用HttpURLConnection来分别构造GET和POST请求,代码如下package com.siwen.net;import java.io.BufferedReader;import java.io.DataOutputStream;import java.io.IOException;import java.io.InputStreamReader;impor
·
一、首先是用HttpURLConnection来分别构造GET和POST请求,代码如下
package com.siwen.net;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Enumeration;
public class TestURL {
private static String getLocalHostIP(){
String hostip = "";
Enumeration<NetworkInterface> allNetInterfaces = null;
try {
allNetInterfaces = NetworkInterface.getNetworkInterfaces();
} catch (SocketException e) {
e.printStackTrace();
}
InetAddress ip = null;
while (allNetInterfaces.hasMoreElements()){
NetworkInterface netInterface = allNetInterfaces.nextElement();
// System.out.println("netInterface:"+netInterface.getName());
Enumeration<InetAddress> addresses = netInterface.getInetAddresses();
while (addresses.hasMoreElements()){
ip = addresses.nextElement();
// System.out.println("InetAddress from "+netInterface.getName()+":"+ip);
if (ip != null && ip instanceof Inet4Address){
if(!ip.getHostAddress().equals("127.0.0.1")){
hostip = ip.getHostAddress();
}
}
}
}
// System.out.println("final hostip:"+hostip);
return hostip;
}
public static void readContentFromGet() throws IOException{
String getURL = "http://"+getLocalHostIP()+":8080/jobticket/sendJobticket?alarmid=test&userName="+URLEncoder.encode("中文", "utf-8")+"&title="+URLEncoder.encode("新告警","utf-8")+"&OperationNotes="+URLEncoder.encode("New Alarm Arrival","utf-8");
URL url = new URL(getURL);
System.out.println("url:"+url);
// 根据拼凑的URL,打开连接,URL.openConnection函数会根据URL的类型返回不同的URLConnection子类的对象,
// 这里URL是一个http,因此实际返回的是HttpURLConnection
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setRequestProperty("Charset", "UTF-8");
// 进行连接,但是实际上get request要在下一句的connection.getInputStream()函数中才会真正发到服务器
connection.connect();
// 取得输入流,并使用Reader读取
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(),"utf-8"));
System.out.println("=============================");
System.out.println("Contents of get request");
System.out.println("=============================");
int incidentId = -1;
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
incidentId = Integer.parseInt(line);
}
reader.close();
// 断开连接
connection.disconnect();
System.out.println("=============================");
System.out.println("Contents of get request ends");
System.out.println("=============================");
System.out.println("incidentId = "+incidentId);
}
public static void readContentFromPost()throws IOException{
// Post请求的url,与get不同的是不需要带参数
String url = "http://"+getLocalHostIP()+":8080/jobticket/sendJobticket";
URL postUrl = new URL(url);
// 打开连接
HttpURLConnection connection = (HttpURLConnection) postUrl.openConnection();
// Output to the connection. Default is false, set to true because post method must write something to the connection
// 设置是否向connection输出,因为这个是post请求,参数要放在 http正文内,因此需要设为true
connection.setDoOutput(true);
// Read from the connection. Default is true.
connection.setDoInput(true);
// Set the post method. Default is GET
connection.setRequestMethod("POST");
// Post cannot use caches
// Post 请求不能使用缓存
connection.setUseCaches(false);
// This method takes effects to every instances of this class.
// URLConnection.setFollowRedirects是static函数,作用于所有的URLConnection对象。
// connection.setFollowRedirects(true);
// This methods only takes effacts to this instance.
// URLConnection.setInstanceFollowRedirects是成员函数,仅作用于当前函数
connection.setInstanceFollowRedirects(true);
// Set the content type to urlencoded,because we will write some URL-encoded content to the connection.
// Settings above must be set before connect!
// 配置本次连接的Content-type,配置为application/x-www-form-urlencoded的
// 意思是正文是urlencoded编码过的form参数,下面我们可以看到我们对正文内容使用URLEncoder.encode进行编码
connection.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
// 连接,从postUrl.openConnection()至此的配置必须要在connect之前完成,
// 要注意的是connection.getOutputStream会隐含的进行connect。
connection.connect();
DataOutputStream out = new DataOutputStream(connection.getOutputStream());
// The URL-encoded contend
// 正文,正文内容其实跟get的URL中'?'后的参数字符串一致
String content = "alarmid=test&userName=" + URLEncoder.encode("中文", "utf-8") + "&title="+URLEncoder.encode("新告警","utf-8")+"&OperationNotes="+URLEncoder.encode("消息内容","utf-8");
// DataOutputStream.writeBytes将字符串中的16位的unicode字符以8位的字符形式写道流里面
out.writeBytes(content);
out.flush();
out.close(); // flush and close
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
int incidentId = -1;
String line;
System.out.println("=============================");
System.out.println("Contents of post request");
System.out.println("=============================");
while ((line = reader.readLine()) != null){
System.out.println(line);
incidentId = Integer.parseInt(line);
}
System.out.println("=============================");
System.out.println("Contents of post request ends");
System.out.println("=============================");
System.out.println("incidentId = "+incidentId);
reader.close();
connection.disconnect();
}
public static void main(String[] args){
try {
readContentFromGet();
readContentFromPost();
} catch (IOException e) {
e.printStackTrace();
}
}
}
二、用Spring mvc编写的服务端代码片段:
package com.pbn.oss.jobticket.client.web;
import java.io.IOException;
import java.util.Map;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import com.pbn.oss.alarm.service.AlarmProcessService;
import com.pbn.oss.fault.ActiveAlarm;
import com.pbn.oss.jobticket.client.service.ClientService;
@Controller
public class JobticketController {
private Logger logger = org.slf4j.LoggerFactory.getLogger(JobticketController.class);
@Resource
private ClientService jobticketService;
@Resource
private AlarmProcessService alarmservice;
public ClientService getJobticketService() {
return jobticketService;
}
public void setJobticketService(ClientService jobticketService) {
this.jobticketService = jobticketService;
logger.info("TechexcelService injection! ClientService="+jobticketService);
}
public AlarmProcessService getAlarmservice() {
return alarmservice;
}
public void setAlarmservice(AlarmProcessService alarmservice) {
this.alarmservice = alarmservice;
}
@RequestMapping(value="/sendJobticket", method = {RequestMethod.GET})
public void sendJobticketGET(HttpServletRequest request,HttpServletResponse response,@RequestHeader Map<String,String> headers,
@RequestParam("alarmid")String alarmid) {
logger.info("===== sendJobticketGET executed! =====");
// logger.info("techexcelService="+jobticketService);
// logger.info("AlarmProcessService="+alarmservice);
try {
// System.out.println("Method:"+request.getMethod());
// System.out.println("===== Header Map:"+headers.size());
// for(Map.Entry<String, String> h : headers.entrySet()){
// System.out.println(h.getKey()+"="+h.getValue());
// }
// System.out.println("==============================");
request.setCharacterEncoding("utf-8");
// when method.equals("POST"):
String userName = request.getParameter("userName");
System.out.println("original userName:"+userName);
String title = request.getParameter("title");
String OperationNotes = request.getParameter("OperationNotes");
if(userName!=null)
userName = new String(userName.getBytes("ISO-8859-1"),"UTF-8");
if(title!=null)
title = new String(title.getBytes("ISO-8859-1"),"UTF-8");
if(OperationNotes!=null)
OperationNotes = new String(OperationNotes.getBytes("ISO-8859-1"),"UTF-8");
// System.out.println("utf-8 userName:"+userName);
// String alarmid = request.getParameter("alarmid");
// String userNameDecode = URLDecoder.decode(userName,"ISO-8859-1");
// String userNameGbk = new String(userName.getBytes("ISO-8859-1"),"GBK");
// System.out.println("decode userName:"+userNameDecode);
// System.out.println("gbk userName:"+userNameGbk);
logger.info("alarmId="+alarmid+" - userName="+userName+" - title="+title+" - desc="+OperationNotes);
if(alarmid.equals("test")){
response.getWriter().write(-1+"");
return;
}
ActiveAlarm alarm = alarmservice.getActiveAlarmById(Long.parseLong(alarmid));
if(alarm == null){
response.getWriter().write(-1+"");
return;
}
int incidentId = jobticketService.sendAlarmToJobTicket(alarm,userName,title,OperationNotes);
response.getWriter().write(incidentId+"");
} catch (IOException e) {
e.printStackTrace();
} catch (NumberFormatException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
@RequestMapping(value="/sendJobticket", method = {RequestMethod.POST})
public void sendJobticketPOST(HttpServletRequest request,HttpServletResponse response,@RequestHeader Map<String,String> headers) {
logger.info("===== sendJobticketPOST executed! =====");
try {
// System.out.println("Method:"+request.getMethod());
// System.out.println("===== Header Map:"+headers.size());
// for(Map.Entry<String, String> h : headers.entrySet()){
// System.out.println(h.getKey()+"="+h.getValue());
// }
// System.out.println("==============================");
request.setCharacterEncoding("utf-8");
// when method.equals("POST"):
String userName = request.getParameter("userName");
String title = request.getParameter("title");
String OperationNotes = request.getParameter("OperationNotes");
String alarmid = request.getParameter("alarmid");
logger.info("alarmId="+alarmid+" - userName="+userName+" - title="+title+" - desc="+OperationNotes);
if(alarmid.equals("test")){
response.getWriter().write(-1+"");
return;
}
ActiveAlarm alarm = alarmservice.getActiveAlarmById(Long.parseLong(alarmid));
if(alarm == null){
response.getWriter().write(-1+"");
return;
}
int incidentId = jobticketService.sendAlarmToJobTicket(alarm,userName,title,OperationNotes);
response.getWriter().write(incidentId+"");
} catch (IOException e) {
e.printStackTrace();
} catch (NumberFormatException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}

GitCode 天启AI是一款由 GitCode 团队打造的智能助手,基于先进的LLM(大语言模型)与多智能体 Agent 技术构建,致力于为用户提供高效、智能、多模态的创作与开发支持。它不仅支持自然语言对话,还具备处理文件、生成 PPT、撰写分析报告、开发 Web 应用等多项能力,真正做到“一句话,让 Al帮你完成复杂任务”。
更多推荐
所有评论(0)