【问题标题】:android http request giving null exceptionandroid http请求给出空异常
【发布时间】:2015-12-29 08:28:39
【问题描述】:

在我的 Android 项目中,我想存储人员数据。 基本的是,填写个人详细信息表后,当按进入时,它将连接到服务器并存储来自服务器的数据。

所以,我有:

 private void serverSignup(final Person suf) {
        new AsyncTask<Person, Void, String>() {
            @Override
            protected String doInBackground(Person... params) {
                String serverResponse = "";

    try {
         serverResponse = mServerAuth.userSignup(suf.getName(),
          suf.getCountry(),suf.getDate(), suf.getEmail());

          } catch (Exception e) {
          Log.e("ErrorMessage", TAG + " > Signup access server error: " + 
          e.getMessage());  **I am getting this section as null

            }
                return serverResponse;
            }

            @Override
            protected void onPostExecute(String serverResponse) {
            finish();

            }
        }.execute();
    }

mServerAuth代码是:

    public String userSignup(String name, String country,
 String date, String email) throws Exception {

            String url = "http://localhost:8080/SpringMVCHibernate/person/add";
            Person suf = new Person(name, country, date, email);
            List<NameValuePair> pairs = new ArrayList<NameValuePair>(1);
            pairs.add(new BasicNameValuePair("suf", new Gson().toJson(suf)));

            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpEntity requestEntity = new UrlEncodedFormEntity(pairs);
            HttpPost httpPost = new HttpPost(url);
            httpPost.setEntity(requestEntity);


            try {

            HttpResponse response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();

            } catch (IOException ioe) {

            Log.e("Error", TAG + " > 
            IOEException during the POST response: " + ioe.getMessage());
            }

            return null;
        }}

访问此代码时出现错误:

Signup access server error: null 为什么值为null??它没有连接到服务器吗??

【问题讨论】:

  • 您是否在您的 Manifest.xml 中添加了正确的权限
  • @Preeti:使用 HTTPUrlConnection 进行 Web 服务请求。
  • @kevz:好的,但是为什么我必须使用“HTTPUrlConnection”? DefaultHttpClient 不支持???
  • @Preeti:是的,它在 Android 的新 API 中已被弃用。

标签: android androidhttpclient


【解决方案1】:

您不要在 Android 中使用已弃用的 API。下面是使用 HTTPUrlConnection api 的代码。希望它有助于实现您的目的。

new AsyncTask < Person, Void, String > () {

String LOGIN_URL = "http://localhost:8080/SpringMVCHibernate/person/add";
HttpURLConnection conn;
DataOutputStream wr;
String responseCode = "-1";
URL url;

@Override
protected String doInBackground(String...params) {

    try {

        url = new URL(LOGIN_URL);
        conn = (HttpURLConnection) url.openConnection();
        conn.setDoOutput(true);
        conn.setRequestMethod("POST");
        conn.connect();


        Person suf = new Person(name, country, date, email);
        String strSuf = new Gson().toJson(suf);

        wr = new DataOutputStream(conn.getOutputStream());
        wr.writeBytes(strSuf);
        wr.close();

        responseCode = conn.getResponseCode();

        return responseCode;

    } catch (IOException e) {
        e.printStackTrace();
    } finally() {
        conn.disconnect();
    }

    return responseCode;
}

@Override
protected void onPostExecute(String responseCode) {

    if (!responseCode.equals("-1"))
        Toast.makeText(mContext, "Stored data successfully", Toast.LENGTH_LONG).show();
    else
        Toast.makeText(mContext, "failed to store data", Toast.LENGTH_LONG).show();
}

}.execute();

【讨论】:

  • @Preeti:使用 HTTPUrlConnection 检查答案。
【解决方案2】:

来自HttpEntity entity = response.getEntity(); 您获取实体对象但未读取数据,很简单,您返回的是 null。

你需要得到这样的响应

HttpResponse httpresponse = httpclient.execute(httppost);
String  response=EntityUtils.toString(httpresponse.getEntity());

那么你需要返回“response”字符串。

同时检查 url 是否有效?

【讨论】:

  • 我也这样做了,但仍然是同样的错误.. 在我的连接中,我使用的是 wifi 上网,我通过“usb teathering”连接我的电脑..在本地主机中我输入电脑 IP 地址..
猜你喜欢
  • 2017-06-13
  • 1970-01-01
  • 1970-01-01
  • 2016-01-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-05-21
相关资源
最近更新 更多