Android中的網絡請求主要有GET和POST方式。POST方式比GET方式更爲安全,因爲需要發送的消息不是嵌入在url中的,同時能比GET發送更多的數據。
本文討論使用POST方式向聚合數據API發送請求,以獲得手機號碼歸屬地的信息。歸屬地查詢的接口的請求示例爲:http://apis.juhe.cn/mobile/get?phone=13429667914&key=您申請的KEY。默認返回的格式爲JSON。最後把返回結果顯示在TextView上。直接上代碼:
-
public class MainActivity extends Activity {
-
-
private TextView text;
-
private String url = "http://apis.juhe.cn/mobile/get";//向服務器請求的url.
-
private Handler handler = new Handler();
-
-
@Override
-
protected void onCreate(Bundle savedInstanceState) {
-
super.onCreate(savedInstanceState);
-
setContentView(R.layout.activity_main);
-
text = (TextView) findViewById(id_text);
-
-
-
new Thread() {
-
@Override
-
public void run() {
-
try {
-
URL httpUrl = new URL(url);
-
HttpURLConnection conn = (HttpURLConnection) httpUrl.openConnection();
-
conn.setReadTimeout(5000);
-
conn.setRequestMethod("POST");
-
-
String content = "phone=13429667914&key=9719c91bd4ac2647c67c6cd067b5cb8e";
-
OutputStream is = conn.getOutputStream();
-
is.write(content.getBytes());
-
-
final StringBuffer sb = new StringBuffer();
-
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
-
String line;
-
while ((line = reader.readLine()) != null) {
-
sb.append(line);
-
}
-
handler.post(new Runnable() {
-
@Override
-
public void run() {
-
text.setText(sb.toString());
-
}
-
});
-
} catch (MalformedURLException e) {
-
e.printStackTrace();
-
} catch (IOException e) {
-
e.printStackTrace();
-
}
-
}
-
}.start();
-
}
-
}
運行程序後,服務器返回的結果如圖:
。成功通過post方式獲取服務器數據。
通過比較GET方式和POST方式,其實兩者是十分類似的。只是POST方式把需要發送的消息單獨抽取出來進行拼接,而不是嵌入到URL中,相對來說更加安全。區別只在於以下4行代碼(把URL中“?”之後的內容抽取出來):
-
private String url = "http://apis.juhe.cn/mobile/get";//向服務器請求的url.
-
-
-
String content = "phone=13429667914&key=9719c91bd4ac2647c67c6cd067b5cb8e";
-
OutputStream is = conn.getOutputStream();
-
is.write(content.getBytes());
這樣就可以方便的進行GET,POST請求了。(對於返回XML格式的就不再贅述了)。
github主頁:https://github.com/chenyufeng1991 。歡迎大家訪問!