我在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名称将在标题中发送。怎么做? –