检查POST是否成功(Android)

时间:2015-06-09 15:03:00

标签: java android post request

我在Android上发帖子请求。它应该以字符串的形式给我一个回应。多数民众赞成我做的检查。但是它给了我一个空字符串。它在toast消息中。我做错了什么,给我们任何暗示吗?

private void makePostRequest() throws UnsupportedEncodingException {
    SharedPreferences postpreference = this.getSharedPreferences("preferences", MODE_PRIVATE);
    String password = postpreference.getString("Password", null);
    String username = postpreference.getString("Username", null);

    String data = URLEncoder.encode("username", "UTF-8") + "=" + URLEncoder.encode(username, "UTF-8");
    data += "&" + URLEncoder.encode("password", "UTF-8") + "=" + URLEncoder.encode(password, "UTF-8");

    String text = "";
    BufferedReader reader = null;

    try {
        // send post data request
        URL url = new URL("secreturl but working");
        URLConnection conn = url.openConnection();

        OutputStreamWriter streamWriter = new OutputStreamWriter(conn.getOutputStream());

        streamWriter.write(data);
        streamWriter.flush();

        //read the response
        reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        StringBuilder sb = new StringBuilder();
        String line = null;

        while ((line = reader.readLine()) != null) {
            // Append server response in string
            sb.append(line + "\n");
        }
        text = sb.toString();
    } catch (Exception ex) {

    } finally {
        try {
            reader.close();
        } catch (Exception e) {

        }
    }
    // Show response on activity
    Toast.makeText(getApplicationContext(), text, Toast.LENGTH_LONG).show();

}

2 个答案:

答案 0 :(得分:0)

检查响应代码。然后,只有获得正确的响应代码才能获得响应。

int responseCode = conn.getResponseCode();

答案 1 :(得分:0)

我按照此链接中的第一个解决方案修复了它:Android, Java: HTTP POST Request

感谢您的帮助

编辑:正确执行发布请求的方法。

HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.yoursite.com/script.php");

try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("id", "12345"));
nameValuePairs.add(new BasicNameValuePair("stringdata", "AndDev is Cool!"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);

} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}