前两天公司很多人来面试,出的一个机试题。向服务器请求数据然后通过json解析出来。发现好多人都不知道怎么做。平时 开发过程中当然是用的各种第三发的开源库,但是面试的时候如果不用as的话,还得下载各种jar,所以还不如用原生的来的实在。
直接上代码吧!
/**
* 向指定 URL 发送POST方法的请求
* @param url 发送请求的 URL
*
* @param param 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
*
* @return 所代表远程资源的响应结果
*/
public static String sendPost(String url, HashMap<String, String> hashUrl ) {
//拼接hashmap参数字符串
String hashString = "";
Iterator iter = hashUrl.entrySet().iterator();
while (iter.hasNext()) {
HashMap.Entry entry = (HashMap.Entry) iter.next();
String key = (String)entry.getKey();
String val = (String)entry.getValue();
try {
hashString += key + "=" + URLEncoder.encode(val, "UTF-8");
} catch (Exception e) {
// TODO: handle exception
}
if(iter.hasNext())
hashString += "&";
}
//输入请求网络日志
System.out.println("post_url="+url);
System.out.println("post_param="+hashString);
BufferedReader in = null;
String result = "";
HttpURLConnection conn = null;
try {
URL realUrl = new URL(url);
// 打开和URL之间的连接
conn = (HttpURLConnection) realUrl.openConnection();
// 设置通用的请求属性
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setConnectTimeout(10000);//设置连接超时
conn.setReadTimeout(10000);//设置读取超时
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
//上传文件 content_type
// conn.setRequestProperty("Content-Type", "multipart/form-data; boudary= 89alskd&&&ajslkjdflkjalskjdlfja;lksdf");
conn.connect();
OutputStreamWriter osw = new OutputStreamWriter(conn.getOutputStream(), "utf-8");
osw.write(hashString);
osw.flush();
osw.close();
if (conn.getResponseCode() == 200) {
in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
result += inputLine;
}
System.out.println("post_result="+result);
in.close();
}
} catch (SocketTimeoutException e ) {
//连接超时、读取超时
e.printStackTrace();
return "POST_Exception";
}catch (ProtocolException e){
e.printStackTrace();
return "POST_Exception";
} catch (IOException e) {
e.printStackTrace();
System.out.println("发送 POST 请求出现异常!"+e.getMessage()+"//URL="+url);
e.printStackTrace();
return "POST_Exception";
}
//使用finally块来关闭输出流、输入流
finally{
try{
if (conn != null) conn.disconnect();
if(in!=null){
in.close();
}
}
catch(IOException ex){
ex.printStackTrace();
}
}
return result;
}
/**
* 获取网落图片资源
*
* @param url
* @return
*/
public static Bitmap getHttpBitmap1(String url,int sc) {
URL m;
InputStream i = null;
BufferedInputStream bis = null;
ByteArrayOutputStream out = null;
if (url == null)
return null;
try
{
m = new URL(url);
i = (InputStream) m.getContent();
bis = new BufferedInputStream(i, 1024 * 4);
out = new ByteArrayOutputStream();
byte[] isBuffer = new byte[1024*4];
int len = 0;
while ((len = bis.read(isBuffer)) != -1)
{
out.write(isBuffer, 0, len);
}
out.close();
bis.close();
} catch (MalformedURLException e1)
{
e1.printStackTrace();
return null;
} catch (IOException e)
{
e.printStackTrace();
}
if (out == null)
return null;
byte[] data = out.toByteArray();
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeByteArray(data, 0, data.length, options);
options.inJustDecodeBounds = false;
int be = (int) (options.outHeight / (float) sc);
if (be <= 0)
{
be = 1;
} else if (be > 3)
{
be = 3;
}
options.inSampleSize = be;
Bitmap bmp =null;
try
{
bmp = BitmapFactory.decodeByteArray(data, 0, data.length, options); //返回缩略图
} catch (OutOfMemoryError e)
{
System.gc();
bmp =null;
}
return bmp;
}
/**
* 获取网落图片资源
* @param url
* @return
*/
public static Bitmap getHttpBitmap(String url){
URL myFileURL;
Bitmap bitmap=null;
try{
myFileURL = new URL(url);
//获得连接
HttpURLConnection conn=(HttpURLConnection)myFileURL.openConnection();
//设置超时时间为6000毫秒,conn.setConnectionTiem(0);表示没有时间限制
conn.setConnectTimeout(6000);
//连接设置获得数据流
conn.setDoInput(true);
//不使用缓存
conn.setUseCaches(false);
//这句可有可无,没有影响
//conn.connect();
//得到数据流
InputStream is = conn.getInputStream();
//解析得到图片
bitmap = BitmapFactory.decodeStream(is);
//关闭数据流
is.close();
}catch(Exception e){
e.printStackTrace();
}
return bitmap;
}
上面两个方法,一个是请求数据,一个是请求网络图片。当然了,不要忘记添加联网权限和开辟子线程执行。