HttpURLConnection请求

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了HttpURLConnection请求相关的知识,希望对你有一定的参考价值。

 

方法调用:

//测试



public static void main(String[] args) {

Map map = new HashMap();

map.put("type", "update" );

map.put("loginName", "4" );

map.put("userpasswd", "96e79218965eb72c92a549dd5a330112" );

map.put("email", "[email protected]" );

JSONObject jsonObject = (JSONObject) JSONObject.toJSON(map);

String strJsonObject=jsonObject.toString();

String url = "http://localhost:8080/xtmc/synchroUser/insertWebUser.do?userData="+strJsonObject;

System.out.println("注册同步 "+url);

String jsonString = HttpRequestUtil.sendPost(url);

System.out.println("返回的结果是"+jsonString);

}

 

 

sendPost(url)方法见链接:

http://www.cnblogs.com/zhuawang/archive/2012/12/08/2809380.html

或者:

/**
* 向指定 URL 发送POST方法的请求
* 
* @param pathUrl 发送请求的 URL
* @return 所代表远程资源的响应结果
*/
public static String sendPost(String pathUrl) {
try { 
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请求方法 
String requestString = "客服端要以以流方式发送到服务端的数据..."; 


// 设置请求属性 
// 获得数据字节数据,请求数据流的编码,必须和下面服务器端处理请求流的编码一致 
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"); 
// 
String name = URLEncoder.encode("黄武艺", "utf-8"); 
httpConn.setRequestProperty("NAME", name); 


// 建立输出流,并写入数据 
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.out.println(sb.toString());
return sb.toString();
} 
} catch (Exception e) { 
System.out.println(e.getStackTrace()); 
} 
return null;
}

 

 

被请求方法(/synchroUser/insertWebUser.do ):

@RequestMapping("/synchroUser/insertWebUser.do")
public void insertWebUser(HttpServletResponse response,HttpServletRequest request,@RequestParam("userData") String userData) throws Exception {
JSONObject dataMap = null;
System.out.println("接收到的userData==="+userData);
try {
dataMap = JSONObject.parseObject(userData);
} catch (Exception e) {
System.out.println("参数解析错误!");
e.printStackTrace();
}

String loginName = getJsonValue(dataMap, "loginName");
String userpasswd = getJsonValue(dataMap, "userpasswd");
String email = getJsonValue(dataMap, "email");
String type = getJsonValue(dataMap, "type");

} catch (Exception e) {
// TODO: handle exception
flag = "false";
e.printStackTrace();
}
response.getWriter().write("success");
}

 

/**
* 获取json对象中的属性
* @param params json对象
* @param key 参数名
* @return
*/
private String getJsonValue(JSONObject params, String key) {
if (params == null || "".equals(key) || key == null) {
return null;
}
Object obj = params.get(key);
return obj == null ? null : obj.toString();
}

 

以上是关于HttpURLConnection请求的主要内容,如果未能解决你的问题,请参考以下文章

HTTP客户端代码片段

Android使用HttpURLConnection,OKHttp发送请求及注意事项

Android使用HttpURLConnection,OKHttp发送请求及注意事项

怎么用http协议实现安卓数据

[Android基础]Android中使用HttpURLConnection

Java利用原始HttpURLConnection发送http请求数据小结