我正在开发一个Android应用程序,它将在远程服务器上的MySQL数据库中保存传入的文本消息。做这个的最好方式是什么?我需要写什么组件?
答案 0 :(得分:0)
通过发帖:)
private void postSms(String text) {
URL url;
HttpURLConnection urlConnection = null;
try {
url = new URL("http://yourserver.com/sendsms");
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("POST");
urlConnection.setDoOutput(true);
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("sms", text));//POST param as "sms"
OutputStream os = urlConnection.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
writer.write(getQuery(params));
writer.flush();
writer.close();
os.close();
String status = new String(Streams.getBytes(urlConnection.getInputStream()));
Log.d(TAG, new Exception().getStackTrace()[0].getMethodName() + ":insert status=" + status);
} catch (MalformedURLException | ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private String getQuery(List<NameValuePair> params) throws UnsupportedEncodingException {
StringBuilder result = new StringBuilder();
boolean first = true;
for (NameValuePair pair : params) {
if (first)
first = false;
else
result.append("&");
result.append(URLEncoder.encode(pair.getName(), "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(pair.getValue(), "UTF-8"));
}
return result.toString();
}
别忘了将此添加到清单
<uses-permission android:name="android.permission.INTERNET" />
或者在blog
上阅读