虽然代码差不多,但是稍微改了些,嘻嘻......非常感谢原帖主。
下面是我改后的代码。(嘻嘻,虽然改后变化不大)
private static String URL = "http://xxx/api/v1/video/Register"; public void regist(){ Map<String, Object> requestParamsMap = new HashMap<String, Object>(); requestParamsMap.put("username", "test11"); requestParamsMap.put("password", "111"); PrintWriter printWriter = null; HttpURLConnection conn = null; BufferedReader bufferedReader = null; StringBuffer responseResult = new StringBuffer(); StringBuffer params = new StringBuffer(); // 组织请求参数 Iterator it = requestParamsMap.entrySet().iterator(); while (it.hasNext()) { Map.Entry element = (Map.Entry) it.next(); params.append(element.getKey()); params.append("="); params.append(element.getValue()); params.append("&"); } if (params.length() > 0) { params.deleteCharAt(params.length() - 1); } try { String newUrl = URL +"?"+ params; //初次接触这东西,就直接拼接在地址上了 URL url = new URL(newUrl); conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST");// 提交模式 conn.setRequestProperty("Content-Type", "plain/text; charset=UTF-8"); // 设置通用的请求属性 conn.setRequestProperty("accept", "*/*"); conn.setRequestProperty("connection", "Keep-Alive"); // 发送POST请求必须设置如下两行 conn.setDoOutput(true); conn.setDoInput(true); conn.connect(); int responseCode = conn.getResponseCode(); if (responseCode != 200) { System.out.println("Not Success"); } else { System.out.println("Success"); } // 定义BufferedReader输入流来读取URL的ResponseData bufferedReader = new BufferedReader(new InputStreamReader( conn.getInputStream())); String line; while ((line = bufferedReader.readLine()) != null) { responseResult.append("/n").append(line); } /* 将Response显示于Dialog */ showDialog("注册成功" + responseResult.toString().trim()); /* 关闭DataOutputStream */ } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); }finally{ conn.disconnect(); try { if (printWriter != null) { printWriter.close(); } if (bufferedReader != null) { bufferedReader.close(); } } catch (IOException ex) { ex.printStackTrace(); } } }
本来不想直接把参数拼接在地址上的,但使用OutputStream输入流老是报404,偷懒直接拼上了。
希望能帮助到别人吧。
时间: 2024-10-22 00:38:47