0
点赞
收藏
分享

微信扫一扫

java中GET方式提交和POST方式提交

雨鸣静声 2022-03-21 阅读 64


java中GET方式提交的示例:

/**
* 获取关注列表;
* @return
*/
@SuppressWarnings("unchecked")
public static ArrayList<String> getUserList() {

StringBuffer bufferRes = new StringBuffer();

ArrayList<String> users = null;

try {

URL realUrl = new URL("https://api.weixin.qq.com/cgi-bin/user/get?access_token=" + TokenProxys.accessTokens());
//URL realUrl = new URL("https://api.weixin.qq.com/cgi-bin/user/tag/get?access_token=" + TokenProxys.accessTokens());

HttpURLConnection conn = (HttpURLConnection)realUrl.openConnection();

// 请求方式

conn.setDoOutput(true);

conn.setDoInput(true);

conn.setRequestMethod("GET");

conn.setUseCaches(false);

conn.setInstanceFollowRedirects(true);

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

conn.connect();

// 获取URLConnection对象对应的输入流

InputStream in =conn.getInputStream();

BufferedReader read =new BufferedReader(new InputStreamReader(in,"UTF-8"));

String valueString =null;

while ((valueString=read.readLine())!=null){

bufferRes.append(valueString);

}

System.out.println(bufferRes);

in.close();

if (conn !=null){

// 关闭连接

conn.disconnect();

}

} catch (Exception e) {

e.printStackTrace();

}

//将返回的字符串转换成json

JSONObject jsonObject = JSONObject.fromObject(bufferRes.toString());

//解析json中表示openid的列表

JSONObject data = (JSONObject)jsonObject.get("data");

if(data!=null){

//将openid列表转化成数组保存

users = new ArrayList<String>(data.getJSONArray("openid"));

//获取关注者总数

int count = Integer.parseInt(jsonObject.get("total").toString());

if(count>1000){

JSONObject object = jsonObject;

String next_openid = null;

JSONObject ob_data = null;

ArrayList<String> ob_user = null;

//大于1000需要多次获取,或许次数为count/1000

for(int i=0;i<count/1000;i++){

//解析出下次获取的启示openid

next_openid = object.get("next_openid").toString();

object = getUserJson(next_openid);

ob_data = (JSONObject)object.get("data");

ob_user = new ArrayList<String>(ob_data.getJSONArray("openid"));

for(String open_id : ob_user){

//将多次获取的openid添加到同一个数组

users.add(open_id);

}

}

}

}

return users;

}


java中POST方式提交的示例1:

public static void main(String[] args) {
try {
String pathUrl = "https://api.weixin.qq.com/cgi-bin/user/tag/get?access_token=zN6OKXWAdBKdwPUc1CFXIW-czck3W1CURoKr38Xy7jjDpyIxrpmSyfglAY1Bnvq3FePZbFVUzpeLfWC9lml7ENeApBJhSDXE-BRrHCmBsTk4gUI6DxxDgrGekrdkUSDkETAhAGAZOV";
// 建立连接
URL url = new URL(pathUrl);
HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();



// //设置连接属性
httpConn.setDoOutput(true);// 使用 URL 连接进行输出
httpConn.setDoInput(true);// 使用 URL 连接进行输入
httpConn.setUseCaches(false);// 忽略缓存
httpConn.setRequestMethod("POST");// 设置URL请求方法
//POST请求设置所需要的JSON数据格式{"tagid" : 134,"next_openid":""//第一个拉取的OPENID,不填默认从头开始拉取}
List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();
Map<String, Object> map = new HashMap<String, Object>();
map.put("tagid", 104);
map.put("next_openid","");
list.add(map);
JSONArray arry=JSONArray.fromObject(map);
String requestString = arry.toString().replace("[", "").replace("]", "");



// 设置请求属性
// 获得数据字节数据,请求数据流的编码,必须和下面服务器端处理请求流的编码一致
byte[] requestStringBytes = requestString.getBytes("utf-8");
httpConn.setRequestProperty("Content-length", "" + requestStringBytes.length);
httpConn.setRequestProperty("Content-Type", "application/octet-stream");
httpConn.setRequestProperty("Connection", "Keep-Alive");// 维持长连接
httpConn.setRequestProperty("Charset", "UTF-8");


// 建立输出流,并写入数据,此方法是同样适用于参数中有文字的方法
OutputStream outputStream = httpConn.getOutputStream();
outputStream.write(requestStringBytes);
outputStream.close();
// 获得响应状态
int responseCode = httpConn.getResponseCode();



if (HttpURLConnection.HTTP_OK == responseCode) {// 连接成功
// 当正确响应时处理数据
StringBuffer sb = new StringBuffer();
String readLine;
BufferedReader responseReader;
// 处理响应流,必须与服务器响应流输出的编码一致
responseReader = new BufferedReader(new InputStreamReader(httpConn.getInputStream(), "utf-8"));
while ((readLine = responseReader.readLine()) != null) {
sb.append(readLine).append("\n");
}
responseReader.close();
System.err.println(sb.toString());
}
} catch (Exception ex) {
ex.printStackTrace();
}

}


 post请求向服务器传递参数的另外一种形式,示例2:

服务器端接受参数:String datas= request.getParameter("datas");

public static void sendPost() throws IOException{
List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();
Map<String, Object> map = new HashMap<String, Object>();
map.put("phone", "phone");
list.add(map);
JSONArray arry=JSONArray.fromObject(map);
String requestString = arry.toString();

String result="";
PrintWriter out = null;
BufferedReader in = null;
String pathUrl = "http://shuilangyizu.iask.in/app/appWechatDataController/wchatInfo.do";
URL url=null;
try {
url = new URL(pathUrl);
URLConnection connect = url.openConnection();
connect.setRequestProperty("content-type","application/x-www-form-urlencoded;charset=utf-8");
connect.setRequestProperty("method","POST");
byte[] bytes= requestString.getBytes("utf-8") ;
connect.setDoOutput(true);
connect.setDoInput(true);

out = new PrintWriter(connect.getOutputStream());
// 发送请求参数:此方式遇到中文容易乱码,所以如果参数中有中文建议用上一种方式
out.print("datas="+requestString);
out.flush();
// 定义BufferedReader输入流来读取URL的响应  
in = new BufferedReader(new InputStreamReader(connect.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
System.out.println(result);
in.close();
out.close();
} catch (Exception e) { // TODO Auto-generated catch block  e.printStackTrace(); } }


post请求向服务器传递参数的形式,示例3:

public static void main(String[] args) {
try {
String pathUrl = "https://shuilangyizu.iask.in/app/order/create";
String appKey = "appkey";
String appSecret = "appsecret";

HttpPost httpPost = new HttpPost(pathUrl);// 请求地址
HttpClient client = new DefaultHttpClient();

//构造POST请求设置所需要的JSON数据格式参数
List<OrderChilden> childenList = new ArrayList<OrderChilden>();
for (int i = 0; i <3 ; i++) {
OrderChilden childen = OrderChilden();
childen.setProductCode("code"+i);
childen.setProductName("name"+i);

childenList.add(childen);
}

OrderVo orderVo = new OrderVo();
orderVo.setOno("0001");
orderVo.setCname("测试客户");
orderVo.setOrders(childenList);

JSONObject object=JSONObject.fromObject(orderVo);
System.out.println(object.toString());

String body = object.toString();

Date date = new Date();
long timestamp = date.getTime();

StringBuffer sba = new StringBuffer();
sba.append(timestamp);

String sign = getSign(pathUrl,timestamp,appSecret,body);

List<NameValuePair> parameters = new ArrayList<NameValuePair>();
httpPost.setHeader("appKey",appKey);
httpPost.setHeader("timestamp", sba.toString());
//httpPost.setHeader("body", body);
httpPost.setHeader("sign", sign);

parameters.add(new BasicNameValuePair("appKey", appKey));
parameters.add(new BasicNameValuePair("appSecret", appSecret));
parameters.add(new BasicNameValuePair("timestamp", sba.toString()));
parameters.add(new BasicNameValuePair("body", body));
parameters.add(new BasicNameValuePair("sign", sign));

JSONObject obj = JSONObject.fromObject(orderVo);

//httpPost.setEntity(new UrlEncodedFormEntity(parameters, Charset.forName("UTF-8")));
httpPost.setEntity(new StringEntity(obj.toString(), ContentType.APPLICATION_JSON));
HttpResponse httpResponse;
Map<String, String> maps = new HashMap<String, String>();
httpResponse = client.execute(httpPost);
BufferedReader reader = new BufferedReader(
new InputStreamReader(httpResponse.getEntity().getContent(), Charset.forName("UTF-8")));
StringBuffer sb = new StringBuffer();
String content = null;
while ((content = reader.readLine()) != null) {
sb.append(content);
}
System.out.println(sb.toString());
reader.close();
} catch (Exception ex) {
ex.printStackTrace();
}

}



接收数据服务器上接收数据的方式,示例1:

@RequestMapping(value = "/synSystemData")
public void synSystemData(HttpServletRequest request, HttpServletResponse response) throws Exception {
boolean isGet = request.getMethod().toLowerCase().equals("get");
response.setCharacterEncoding("utf-8"); //设置 HttpServletResponse使用utf-8编码 防止中文乱码
     response.setHeader("Content-Type", "text/html;charset=utf-8"); //设置响应头的编码 防止中文乱码
if (!isGet) {
String inputLine;
String notityJson = "";
try {
while ((inputLine = request.getReader().readLine()) != null) {
notityJson += inputLine;
}
request.getReader().close();
} catch (Exception e) {
e.printStackTrace();
}
if(StringUtil.isEmpty(notityJson )){
notityJson = request.getParameter("content");
}
String json= java.net.URLDecoder.decode(notityJson , "UTF-8");
if(StringUtils.isNotEmpty(json)){
StringBuffer sb = new StringBuffer();
         sb.append("ok");
response.getWriter().write(sb.toString());
}

}
}



 接收数据服务器上接收数据的方式,示例2:

/**
* 接收从发送数据服务器传过来的json串
* @param request
* @param response
* @throws Exception
*/
@RequestMapping(value = "/synSystemData")
public void synSystemData(HttpServletRequest request, HttpServletResponse response) throws Exception{
String result = "error";
boolean isPost = request.getMethod().toLowerCase().equals("post");
PrintWriter wirte = null;
wirte = response.getWriter();
response.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");

if (isPost) {
String json = request.getParameter("datas");
System.out.println(json);
wirte.print(result);
}else{
wirte.print("");
}
wirte.flush();
wirte.close();
}





举报

相关推荐

0 条评论