我在android中製作一個簡單的登錄表單,在這個表單中我需要通過標題將os-name和版本號發送到服務器,使用我擁有的web-service api。我是一個初學者,在android中addHeader等方法已經被棄用了。可以有人請幫我弄清楚如何可以添加 這裏是我的代碼:將數據標題中的數據發佈到android中的Web服務器?
登錄:我想POST的os名稱,os_version字段在頭到服務器。我怎樣才能做到這一點?下面是我的代碼
String user = editText_name.getText().toString();
String pass =editText_pass.getText().toString();
JSONObject jsonObject = new JSONObject();
jsonObject.put("user_name",user);
jsonObject.put("password",pass);
String url = WsUtils.BASE_URL+WsUtils.WS_LOGIN;
if (jsonObject.length() > 0) {
new sendJsonData().execute(getPostDataString(jsonObject),url);
}else Toast.makeText(this, "ERROR", Toast.LENGTH_SHORT).show();
sendJsonData():: >>
public class sendJsonData extends AsyncTask<String, Void, String> {
ProgressDialog progressDialog;
String Jsonresponse = null;
@Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = new ProgressDialog(MainActivity.this);
progressDialog.setMessage("please wait");
progressDialog.setCancelable(false);
progressDialog.show();
}
@Override
protected String doInBackground(String... params) {
String Jsondata = params[0];
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
try {
URL url = new URL(params[1]);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setDoOutput(true);
urlConnection.setRequestMethod("POST");
urlConnection.setConnectTimeout(10000);
urlConnection.setRequestProperty("Accept","application/json");
//urlConnection.setRequestProperty("Content-Type","application/json");
OutputStream out = urlConnection.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out, "UTF-8"));
writer.write(Jsondata);
writer.flush();
writer.close();
out.close();
Log.e("json", Jsondata);
DataInputStream in = new DataInputStream(urlConnection.getInputStream());
Jsonresponse = convertStreamToString(in);
return Jsonresponse;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
progressDialog.dismiss();
Log.e("response", Jsonresponse);
}
}
getPostDataString() - >`
public String getPostDataString(JSONObject params) throws Exception {
StringBuilder result = new StringBuilder();
boolean first = true;
Iterator<String> itr = params.keys();
while(itr.hasNext()){
String key= itr.next();
Object value = params.get(key);
if (first)
first = false;
else
result.append("&");
result.append(URLEncoder.encode(key, "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(value.toString(), "UTF-8"));
}
return result.toString();
}
因此,如果我將應用程序的os名稱作爲字段發送到服務器,那麼我應該在setrequestproperty()方法中使用哪個鍵? –
os的名字?它是您想要發送到服務器的自定義數據嗎? – Alan
yaa!實際上我需要將os名稱與數據用戶名和密碼一起發送到服務器。但os名稱將在標題中發送。怎麼做? –