使用 HttpURLConnection 呼叫 WebService
public String postRequest(String requestURL, JSONObject postDataParams) {
URL url;
String response = "";
try {
url = new URL(requestURL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(30000);
conn.setConnectTimeout(30000);
conn.setRequestMethod("POST");
conn.setDoInput(true);
//== 設置此設定,才會真正的使用POST方式,反之 GET 時需改為 false
conn.setDoOutput(true);
String message = postDataParams.toString();
conn.setFixedLengthStreamingMode(message.getBytes().length);
//make some HTTP header nicety
conn.setRequestProperty("Content-Type", "application/json;charset=utf-8");
conn.setRequestProperty("X-Requested-With", "XMLHttpRequest");
//open
conn.connect();
//setup send
OutputStream os = new BufferedOutputStream(conn.getOutputStream());
os.write(message.getBytes());
//clean up
os.flush();
os.close();
int responseCode = conn.getResponseCode();
if (responseCode == HttpsURLConnection.HTTP_OK) {
String line;
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
while ((line = br.readLine()) != null) {
response += line;
}
} else {
response = "";
}
} catch (Exception e) {
e.printStackTrace();
}
return response;
}
private void callApi() {
String res = postRequest(requestURL, postDataParams);
// 轉為 JSONObject
JSONObject jObj = new JSONObject(res);
}
使用 Volley 呼叫 WebService
Android呼叫Web Service請若非處理大量資料時,可使用Volley,此為Google所開發的一套網路框架,把Http請求和執行緒封裝起來,開發者可簡單的呼叫與使用。若需處理大量資料的話,仍需使用HttpURLConnection,並配合前項說明的AsyncTask來處理流程。
若需使用請在Gradle中設定下列參數
compile 'com.android.volley:volley:1.0.0'
建立JsonObject請求
final String url = "http://test.com/api/hello";
JSONObject params = new JSONObject();
params.put("name", "Polory");
params.put("age", "10");
// 建立Request
JsonObjectRequest getRequest = new JsonObjectRequest(
Request.Method.GET, url, null,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
Log.d("Response", response.toString());
}},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.d("Error.Response", response);
}});
建立StringObject請求
StringRequest stringRequest = new StringRequest(
Request.Method.POST, url,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Log.d("Response", response);
}},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.d("Error.Response", response);
}})
{
@Override
protected Map<String, String> getParams()
{
Map<String, String> params = new HashMap<String,String>();
params.put("name", "Polory");
params.put("age", "10");
return params;
}
};