HttpUrlConnection POST请求

本文介绍了一个使用Java发送HTTP POST请求的具体实现方法,包括连接设置、参数传递及响应处理等关键步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

protected static void setHttp(String strUrl,String strPhoneNumber) {
		//TODO 网络请求
		try{
			//建立连接
			URL url=new URL(strUrl);
			HttpURLConnection httpConn=(HttpURLConnection)url.openConnection();
			//设置参数
			httpConn.setDoOutput(true);   //需要输出
			httpConn.setDoInput(true);   //需要输入
			httpConn.setUseCaches(false);  //不允许缓存
			httpConn.setRequestMethod("POST");   //设置POST方式连接
			//设置请求属性
			httpConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
			httpConn.connect();
			DataOutputStream out = new DataOutputStream(httpConn.getOutputStream());
	        String params = "phones=" + URLEncoder.encode(strPhoneNumber, "UTF-8");
	        // DataOutputStream.writeBytes将字符串中的16位的unicode字符以8位的字符形式写到流里面
	        out.writeBytes(params);
	        out.flush();
	        out.close(); 
			//获得响应状态
			int resultCode=httpConn.getResponseCode();
			if(resultCode == 200){
				//响应成功
				InputStream is = httpConn.getInputStream(); // 获取输入流  
				byte[] data = readStream(is); // 把输入流转换成字符串组  
				String json = new String(data); // 把字符串组转换成字符串  
				JSONObject jsonObject = new JSONObject(json); // 返回的数据形式是一个Object类型,所以可以直接转换成一个Object  
				String msgid = jsonObject.getString("msgid");
				String result = jsonObject.getString("result");
				String desc = jsonObject.getString("desc");
				String failPhones = jsonObject.getString("failPhones");
				if("0".equals(result)){
					Log.d("tag", msgid+"\n"+desc+"\n"+failPhones);
				}else if("-1".equals(result)){
					Log.e("tag", desc);
				}
				is.close();
			}else {
				Log.e("tag", "请求失败");
			}
		}catch (Exception e) {
			e.printStackTrace();
		}
	}
	/**
	 * 把输入流转换成字符串数组
	 * @param inputStream
	 * @return 
	 * @throws Exception
	 */
	private static byte[] readStream(InputStream inputStream) throws Exception {  
		ByteArrayOutputStream out = new ByteArrayOutputStream();  
		byte[] buffer = new byte[1024];  
		int len = 0;  
		while ((len = inputStream.read(buffer)) != -1) {  
			out.write(buffer, 0, len);  
		}  
		out.close();  
		inputStream.close();  
		return out.toByteArray();  
	}



参考:
 publicvoid addByUrl() throws Exception{
        String encoding="UTF-8";
        String params="[{\"addTime\":\"2011-09-19 14:23:02\"[],\"iccid\":\"1111\",\"id\":0,\"imei\":\"2222\",\"imsi\":\"3333\",\"phoneType\":\"4444\",\"remark\":\"aaaa\",\"tel\":\"5555\"}]";
        String path ="http://localhost:8083/xxxx/xxx/sim!add.do";
        byte[] data = params.getBytes(encoding);
        URL url =new URL(path);
        HttpURLConnection conn = (HttpURLConnection)url.openConnection();
        conn.setRequestMethod("POST");
        conn.setDoOutput(true);
        //application/x-javascript text/xml->xml数据 application/x-javascript->json对象 application/x-www-form-urlencoded->表单数据
        conn.setRequestProperty("Content-Type", "application/x-javascript; charset="+ encoding);
        conn.setRequestProperty("Content-Length", String.valueOf(data.length));
        conn.setConnectTimeout(5*1000);
        OutputStream outStream = conn.getOutputStream();
        outStream.write(data);
        outStream.flush();
        outStream.close();
        System.out.println(conn.getResponseCode()); //响应代码 200表示成功
        if(conn.getResponseCode()==200){
            InputStream inStream = conn.getInputStream();   
            String result=new String(StreamTool.readInputStream(inStream), "UTF-8");
        }
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值