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"); } }