http发送get/post请求:
public static void main(String[] args) {
//发送get请求
String geturl = "127.0.0.1:8080/user/serviceapi.do?operation=getUser&userID=" + 1234;
OkhttpUtil.syncGet(geturl);
//发送post请求
String posturl = "127.0.0.1:8080/user/serviceapi.do?operation=getUserModel";
JSONObject jsonStr = new JSONObject();
jsonStr.put("username", "李白");
jsonStr.put("studentid", "2018001");
OkhttpUtil.syncPost(posturl, jsonStr.toString());
}
struts框架中获取请求过来的数据:
获取get过来的请求:
@Component("/user/serviceapi")
public class ApiAction extends DispatchAction{
public void getUser(ActionMapping mapping,ActionForm form,
HttpServletRequest request,HttpServletResponse response){
String userID = request.getParameter("userID");
HttpClientUtil.writeJSONStringToClient(response, "success");
}
}
获取post过来的请求:
@Component("/user/serviceapi")
public class ApiAction extends DispatchAction{
public void getUserModel(ActionMapping mapping,ActionForm form,
HttpServletRequest request,HttpServletResponse response){
ActionContext ctx = ActionContext.getContext();
String jsonStr = this.getRequestBody(ctx,request);
JSONObject json = JSONObject.fromObject(jsonStr);
if(json.containsKey("username")){
String username = json.getString("username");
}
if(json.containsKey("studentid")){
String studentid = json.getString("studentid");
}
HttpClientUtil.writeJSONStringToClient(response, "success");
}
public String getRequestBody(ActionContext ctx,HttpServletRequest request){
try {
InputStream inputStream = request.getInputStream();
String strMessage = "";
StringBuffer buff = new StringBuffer();
BufferedReader bufferReader = new BufferedReader(new
InputStreamReader(inputStream,"utf-8"));
while((strMessage = bufferReader.readLine()) != null){
buff.append(strMessage);
}
bufferReader.close();
inputStream.close();
return buff.toString();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}