这是一个使用 AsyncTask 的 http post 示例:
public class httpSendrequest extends AsyncTask<Void,Void,String> {
ArrayList<NameValuePair> nvPairs=new ArrayList<>();
Boolean error=false;
@Override
protected void onPreExecute() {
super.onPreExecute();
//here you initialize your json object and add it to value pairs
JSONObject jObj = new JSONObject();
try {
JSONObject userCredentials = new JSONObject();
userCredentials.put("nickname","nickname6");
userCredentials.put("password","1234");
jObj.put("user", userCredentials);
nvPairs.add(new BasicNameValuePair("jsonstring",jObj.toString()));
} catch(Exception e) {
error=true;
}
}
@Override
protected String doInBackground(Void... params) {
if(!error)
try{
String link ="http://"+ip+"/QSystem.asmx/insert_answer" ;
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(link); //adding URL to the http post
httppost.setEntity(new UrlEncodedFormEntity(nvPairs, HTTP.UTF_8)); //adding the value pairs and encoding to the http post request
HttpResponse response = httpclient.execute(httppost);
HttpEntity resEntity = response.getEntity();
} catch (Exception e){
error=true;
}
return "str";
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
if(!error) {
Toast.makeText(getApplicationContext(), "Sent", Toast.LENGTH_SHORT).show();
}
}
}
然后您可以从 onCreate 或在 OnClickListener 中为按钮调用它,如下所示:
new httpSendrequest().execute();
希望这可以帮助 :)