我有一个与WebService
. 我的应用程序向用php
. php端,只是处理请求并echo
输出JSON
格式的结果。
尽管传输的数据量很少,但有时在我的应用程序中加载数据需要很长时间。
这是我的 android 应用程序中负责发送请求和检索响应的方法
/**
* Posts data to server.
*
* @param url Server URL
* @param json {@link JSONObject} to be sent
* @param tag Tag. used to describe the request
* @return {@link HttpResponse}
* @throws IOException
* @throws ClientProtocolException
*/
public HttpResponse postData(String url, JSONObject json, String tag)
throws ClientProtocolException, IOException {
SharedPreferences prefs = context.getSharedPreferences(SUPPORTDESK, Context.MODE_PRIVATE);
HttpResponse httpResponse = null;
String jsonString = json.toString();
String encodedURL = URLEncoder.encode(jsonString, HTTP.UTF_8);
List<NameValuePair> value = new ArrayList<NameValuePair>();
value.add(new BasicNameValuePair("username", prefs.getString(USERNAME_KEY, "")));
value.add(new BasicNameValuePair("password", prefs.getString(PASSWORD_KEY, "")));
value.add(new BasicNameValuePair("tag", tag));
value.add(new BasicNameValuePair("data", encodedURL));
DefaultHttpClient httpClient = new DefaultHttpClient();
//setTimeout(httpClient, 5000);
HttpPost request = new HttpPost(url);
// StringEntity entity = new StringEntity(jsonString);
// request.setHeader("Content-Type", "application/json");
// request.setEntity(entity);
request.setEntity(new UrlEncodedFormEntity(value, HTTP.UTF_8));
httpResponse = httpClient.execute(request);
return httpResponse;
}
/**
* Retrieves String representation of {@link HttpResponse}
*
* @param response {@link HttpResponse}
* @return <b>String</b> Actual Response from server as string.
* @throws IOException
* @throws IllegalStateException
* @throws UnsupportedEncodingException
*/
public static String getServerResponse(HttpResponse response)
throws IOException, IllegalStateException,
UnsupportedEncodingException {
InputStream is = response.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(is,
HTTP.UTF_8), 100);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
String out = URLDecoder.decode(sb.toString().trim(), HTTP.UTF_8).trim();
int ascii = (int) out.charAt(0);
return (ascii >= 33 & ascii <= 126)?out:out.substring(1);
}
postData
方法将发送请求并等待响应,然后响应将传递getServerResponse
给检索响应的字符串表示形式。当然,所有long-Running
代码都包含在AsyncTask
类中。
这是我的网络服务的示例方法:
function transactionDetail($json) {
$array = json_decode($json, TRUE);
$db = new DBHelper();
$transactionId = $array[$db->JS_RP_TRANSACTION_ID];
$response = $db->getTransactionDetails($transactionId);
echo urlencode(json_encode($response));
}
那么,我在Android 端用于发出请求和检索响应的方法是标准的方法,还是有更好的方法?
如何为我发出的请求设置超时?,您可以在我的代码中看到一条注释行,我试图设置超时,但它破坏了代码。
我使用的代码组合是否Client/Server side
足够好,或者有更多标准或改进的方法来实现这一点,我不知道?