編輯:關於Android編程
/**
* 以get方式向服務端發送請求,並將服務端的響應結果以字符串方式返回。如果沒有響應內容則返回空字符串
*
* @param url 請求的url地址
* @param params 請求參數
* @param charset url編碼采用的碼表
* @return
*/
public static String getDataByGet(String url,Map params,String charset)
{
if(url == null)
{
return ;
}
url = url.trim();
URL targetUrl = null;
try
{
if(params == null)
{
targetUrl = new URL(url);
}
else
{
StringBuilder sb = new StringBuilder(url+?);
for(Map.Entry me : params.entrySet())
{
// 解決請求參數中含有中文導致亂碼問題
sb.append(me.getKey()).append(=).append(URLEncoder.encode(me.getValue(),charset)).append(&);
}
sb.deleteCharAt(sb.length()-1);
targetUrl = new URL(sb.toString());
}
Log.i(TAG,get:url----->+targetUrl.toString());//打印log
HttpURLConnection conn = (HttpURLConnection) targetUrl.openConnection();
conn.setConnectTimeout(3000);
conn.setRequestMethod(GET);
conn.setDoInput(true);
int responseCode = conn.getResponseCode();
if(responseCode == HttpURLConnection.HTTP_OK)
{
return stream2String(conn.getInputStream(),charset);
}
} catch (Exception e)
{
Log.i(TAG,e.getMessage());
}
return ;
/**
* 以post方式向服務端發送請求,並將服務端的響應結果以字符串方式返回。如果沒有響應內容則返回空字符串
* @param url 請求的url地址
* @param params 請求參數
* @param charset url編碼采用的碼表
* @return
*/
public static String getDataByPost(String url,Map params,String charset)
{
if(url == null)
{
return ;
}
url = url.trim();
URL targetUrl = null;
OutputStream out = null;
try
{
targetUrl = new URL(url);
HttpURLConnection conn = (HttpURLConnection) targetUrl.openConnection();
conn.setConnectTimeout(3000);
conn.setRequestMethod(POST);
conn.setDoInput(true);
conn.setDoOutput(true);
StringBuilder sb = new StringBuilder();
if(params!=null && !params.isEmpty())
{
for(Map.Entry me : params.entrySet())
{
// 對請求數據中的中文進行編碼
sb.append(me.getKey()).append(=).append(URLEncoder.encode(me.getValue(),charset)).append(&);
}
sb.deleteCharAt(sb.length()-1);
}
byte[] data = sb.toString().getBytes();
conn.setRequestProperty(Content-Type,application/x-www-form-urlencoded);
conn.setRequestProperty(Content-Length, String.valueOf(data.length));
out = conn.getOutputStream();
out.write(data);
Log.i(TAG,post:url----->+targetUrl.toString());//打印log
int responseCode = conn.getResponseCode();
if(responseCode == HttpURLConnection.HTTP_OK)
{
return stream2String(conn.getInputStream(),charset);
}
} catch (Exception e)
{
Log.i(TAG,e.getMessage());
}
return ;
}
/**
* 將輸入流對象中的數據輸出到字符串中返回
* @param in
* @return
* @throws IOException
*/
private static String stream2String(InputStream in,String charset) throws IOException
{
if(in == null)
return ;
byte[] buffer = new byte[1024];
ByteArrayOutputStream bout = new ByteArrayOutputStream();
int len = 0;
while((len = in.read(buffer)) !=-1)
{
bout.write(buffer, 0, len);
}
String result = new String(bout.toByteArray(),charset);
in.close();
return result;
}
使用httpClient:
package cn.edu.chd.httpclientdemo.http;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import android.util.Log;
/**
* @author Rowand jj
*
*http工具類,發送get/post請求
*/
public final class HttpUtils
{
private static final String TAG = HttpUtils;
private static final String CHARSET = utf-8;
private HttpUtils(){}
/**
* 以get方式向指定url發送請求,將響應結果以字符串方式返回
* @param uri
* @return 如果沒有響應數據返回null
*/
public static String requestByGet(String url,Map data)
{
if(url == null)
return null;
// 構建默認http客戶端對象
HttpClient client = new DefaultHttpClient();
try
{
// 拼裝url,並對中文進行編碼
StringBuilder sb = new StringBuilder(url+?);
if(data != null)
{
for(Map.Entry me : data.entrySet())
{
sb.append(URLEncoder.encode(me.getKey(),CHARSET)).append(=).append(URLEncoder.encode(me.getValue(),utf-8)).append(&);
}
sb.deleteCharAt(sb.length()-1);
}
Log.i(TAG, [get]--->uri:+sb.toString());
// 創建一個get請求
HttpGet get = new HttpGet(sb.toString());
// 執行get請求,獲取http響應
HttpResponse response = client.execute(get);
// 獲取響應狀態行
StatusLine statusLine = response.getStatusLine();
//請求成功
if(statusLine != null && statusLine.getStatusCode() == 200)
{
// 獲取響應實體
HttpEntity entity = response.getEntity();
if(entity != null)
{
return readInputStream(entity.getContent());
}
}
} catch (Exception e)
{
e.printStackTrace();
}
return null;
}
/**
* 以post方式向指定url發送請求,將響應結果以字符串方式返回
* @param url
* @param data 以鍵值對形式表示的信息
* @return
*/
public static String requestByPost(String url,Map data)
{
if(url == null)
return null;
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
List params = null;
try
{
Log.i(TAG, [post]--->uri:+url);
params = new ArrayList();
if(data != null)
{
for(Map.Entry me : data.entrySet())
{
params.add(new BasicNameValuePair(me.getKey(),me.getValue()));
}
}
// 設置請求實體
post.setEntity(new UrlEncodedFormEntity(params,CHARSET));
// 獲取響應信息
HttpResponse response = client.execute(post);
StatusLine statusLine = response.getStatusLine();
if(statusLine!=null && statusLine.getStatusCode()==200)
{
HttpEntity entity = response.getEntity();
if(entity!=null)
{
return readInputStream(entity.getContent());
}
}
} catch (Exception e)
{
e.printStackTrace();
}
return null;
}
/**
* 將流中的數據寫入字符串返回
* @param is
* @return
* @throws IOException
*/
private static String readInputStream(InputStream is) throws IOException
{
if(is == null)
return null;
ByteArrayOutputStream bout = new ByteArrayOutputStream();
int len = 0;
byte[] buf = new byte[1024];
while((len = is.read(buf))!=-1)
{
bout.write(buf, 0, len);
}
is.close();
return new String(bout.toByteArray());
}
/**
* 將流中的數據寫入字符串返回,以指定的編碼格式
* 【如果服務端返回的編碼不是utf-8,可以使用此方法,將返回結果以指定編碼格式寫入字符串】
* @param is
* @return
* @throws IOException
*/
private static String readInputStream(InputStream is,String charset) throws IOException
{
if(is == null)
return null;
ByteArrayOutputStream bout = new ByteArrayOutputStream();
int len = 0;
byte[] buf = new byte[1024];
while((len = is.read(buf))!=-1)
{
bout.write(buf, 0, len);
}
is.close();
return new String(bout.toByteArray(),charset);
}
}
3.使用async-http框架,這個如果使用的話需要導入框架的jar包或者把源碼拷到工程下: 這個框架的好處是每次請求會開辟子線程,不會拋networkonmainthread異常,另外處理器類繼承了Handler類,所以可以在裡面更改UI。 注:這裡使用的是最新的1.4.4版。 ·
/**
* 使用異步http框架發送get請求
* @param path get路徑,中文參數需要編碼(URLEncoder.encode)
*/
public void doGet(String path)
{
AsyncHttpClient httpClient = new AsyncHttpClient();
httpClient.get(path, new AsyncHttpResponseHandler(){
@Override
public void onSuccess(int statusCode, Header[] headers, byte[] responseBody)
{
if(statusCode == 200)
{
try
{
// 此處應該根據服務端的編碼格式進行編碼,否則會亂碼
tv_show.setText(new String(responseBody,utf-8));
} catch (UnsupportedEncodingException e)
{
e.printStackTrace();
}
}
}
});
}
/**
* 使用異步http框架發送get請求
* @param path
*/
public void doPost(String path)
{
AsyncHttpClient httpClient = new AsyncHttpClient();
RequestParams params = new RequestParams();
params.put(paper,中文);//value可以是流、文件、對象等其他類型,很強大!!
httpClient.post(path, params, new AsyncHttpResponseHandler(){
@Override
public void onSuccess(int statusCode, Header[] headers, byte[] responseBody)
{
if(statusCode == 200)
{
tv_show.setText(new String(responseBody));
}
}
});
}
上面那個tv_show是一個TextView控件。
Android應用開發中View繪制的一些優化點解析
一個通常的錯誤觀念就是使用基本的布局結構(例如:LinearLayout、FrameLayout等)能夠在大多數情況下 產生高效率 的
Android 6.0 運行時在Fragment中申請權限無法回調 問題
解決方案:在Fragment中申請權限,不要使用ActivityCompat.requestPermissions, 直接使用Fragment的requestPermis
自定義Adapter並通過布局泵LayoutInflater抓取layout模板編輯每一個item實現思路
寫在前面的話: 看到標題這麼長可能大家有點抓狂了,是的,我在剛剛學這一篇的時候有一些不理解,什麼是布局泵?編輯每一個模板然後什麼是自定義Adapter?下面我們開始學習這
GreenDao 在 Android Studio 中的配置使用
GreenDao的GitHub地址:https://github.com/greenrobot/greenDAO新建gradle空白項目,項目結構如下:新建”