首页 > 解决方案 > 发布请求 JSON 返回 null

问题描述

当我将 mu url 放入邮递员并将我的 3 个参数放入正文时,我发现响应内容是代码或在 android 中我的变量内容响应返回“null”

我不明白为什么。

我的课:

public  class task extends AsyncTask<URL, Void, Void> {
private Context applicationContext;
public HttpEntity responseBody;
public  static String respons;
MainActivity activity;
public  task(MainActivity activity){
  this.activity=activity;
}


@Override
public Void doInBackground(URL... voids) {
    respons=new String("");

    HttpClient httpclient = new DefaultHttpClient();

   HttpPost httppost = new HttpPost("http://recrutement.stb.com.tn:1010/PlateformeApi_Externe/api/");
 
    // Add your data
    List<NameValuePair> nameValuePairs = new ArrayList< NameValuePair >(5);
    nameValuePairs.add(new BasicNameValuePair("username", "sami"));
    nameValuePairs.add(new BasicNameValuePair("password", "stb"));
    nameValuePairs.add(new BasicNameValuePair("AuthMethod", 
    "FormsAuthentication"));
    try {
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        Log.d("myapp", "works till here. 2");
        try {
            HttpResponse response = httpclient.execute(httppost);
            Log.d("myapp", "response " + EntityUtils.toString(response.getEntity()));
           respons = String.valueOf((response.getEntity()));
          // respons=response.
          // responseBody=(response.getEntity());

        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }


    return null;
   }

@Override
protected void onPostExecute(Void aVoid) {
    super.onPostExecute(aVoid);
    String s=respons;
  }

   @Override
     protected void onPreExecute() {
    //Show something on ui like Progress Dialog etc here
    super.onPreExecute();

  }

    public Context getApplicationContext() {
    return applicationContext;
  }

  }                

MainActivity :我打电话给我的班级,我在 toast 消息中看到了我的变量

 public class MainActivity extends AppCompatActivity {                                       
 Button bo;
 URL url;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_main);
    bo=findViewById(R.id.button);
    bo.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            task logIn = new task(MainActivity.this);
            logIn.execute(); 
           Toast.makeText(MainActivity.this,"code="+logIn.respons,Toast.LENGTH_LONG).show();
      
        }
    });
  }
}

我的结果

标签: android

解决方案


推荐阅读