/**
* 從網絡獲取json數據,(String byte[})
* @param path
* @return
*/
public static String getJsonByInternet(String path){
try {
URL url = new URL(path.trim());
//打開連接
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
if(200 == urlConnection.getResponseCode()){
//得到輸入流
InputStream is =urlConnection.getInputStream();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
while(-1 != (len = is.read(buffer))){
baos.write(buffer,0,len);
baos.flush();
}
return baos.toString("utf-8");
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
//獲取其他頁面的數據
/**
* POST請求獲取數據
*/
public static String postDownloadJson(String path,String post){
URL url = null;
try {
url = new URL(path);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");// 提交模式
// conn.setConnectTimeout(10000);//連接超時 單位毫秒
// conn.setReadTimeout(2000);//讀取超時 單位毫秒
// 發送POST請求必須設置如下兩行
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
// 獲取URLConnection對象對應的輸出流
PrintWriter printWriter = new PrintWriter(httpURLConnection.getOutputStream());
// 發送請求參數
printWriter.write(post);//post的參數 xx=xx&yy=yy
// flush輸出流的緩沖
printWriter.flush();
//開始獲取數據
BufferedInputStream bis = new BufferedInputStream(httpURLConnection.getInputStream());
ByteArrayOutputStream bos = new ByteArrayOutputStream();
int len;
byte[] arr = new byte[1024];
while((len=bis.read(arr))!= -1){
bos.write(arr,0,len);
bos.flush();
}
bos.close();
return bos.toString("utf-8");
} catch (Exception e) {
e.printStackTrace();
}
return null;
}