简体   繁体   English

该HTML帖子的响应应该出现在哪里?

[英]Where is the response supposed to appear for this HTML post?

So im practicing with this code from here and i was wondering where the result returns to? 所以我从这里开始练习这段代码,我想知道结果返回到哪里?

For example, i purposely change the url to make it invalid, and i don't see a response with Did not work! 例如,我有意更改URL以使其无效,并且看不到“没有起作用”的响应 anywhere. 任何地方。 I looked at the console , logcat , and no sign of any indicator of if the post was successful or not . 我看了看consolelogcat ,没有任何迹象表明发布是否成功

How can i find this out? 我如何找到这个? Thanks! 谢谢!

public class MainActivity extends Activity implements OnClickListener {

TextView tvIsConnected;
EditText etName,etCountry,etTwitter;
Button btnPost;

Person person;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    // get reference to the views
    tvIsConnected = (TextView) findViewById(R.id.tvIsConnected);
    etName = (EditText) findViewById(R.id.etName);
    etCountry = (EditText) findViewById(R.id.etCountry);
    etTwitter = (EditText) findViewById(R.id.etTwitter);
    btnPost = (Button) findViewById(R.id.btnPost);

    // check if you are connected or not
    if(isConnected()){
        tvIsConnected.setBackgroundColor(0xFF00CC00);
        tvIsConnected.setText("You are conncted");
    }
    else{
        tvIsConnected.setText("You are NOT conncted");
    }

    // add click listener to Button "POST"
    btnPost.setOnClickListener(this);

}

public static String POST(String url, Person person){
    InputStream inputStream = null;
    String result = "";
    try {

        // 1. create HttpClient
        HttpClient httpclient = new DefaultHttpClient();

        // 2. make POST request to the given URL
        HttpPost httpPost = new HttpPost(url);

        String json = "";

        // 3. build jsonObject
        JSONObject jsonObject = new JSONObject();
        jsonObject.accumulate("name", person.getName());
        jsonObject.accumulate("country", person.getCountry());
        jsonObject.accumulate("twitter", person.getTwitter());

        // 4. convert JSONObject to JSON to String
        json = jsonObject.toString();

        // ** Alternative way to convert Person object to JSON string usin Jackson Lib 
        // ObjectMapper mapper = new ObjectMapper();
        // json = mapper.writeValueAsString(person); 

        // 5. set json to StringEntity
        StringEntity se = new StringEntity(json);

        // 6. set httpPost Entity
        httpPost.setEntity(se);

        // 7. Set some headers to inform server about the type of the content   
        httpPost.setHeader("Accept", "application/json");
        httpPost.setHeader("Content-type", "application/json");

        // 8. Execute POST request to the given URL
        HttpResponse httpResponse = httpclient.execute(httpPost);

        // 9. receive response as inputStream
        inputStream = httpResponse.getEntity().getContent();

        // 10. convert inputstream to string
        if(inputStream != null)
            result = convertInputStreamToString(inputStream);
        else
            result = "Did not work!";

    } catch (Exception e) {
        Log.d("InputStream", e.getLocalizedMessage());
    }

    // 11. return result
    return result;
}

public boolean isConnected(){
    ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Activity.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
        if (networkInfo != null && networkInfo.isConnected()) 
            return true;
        else
            return false;    
}
@Override
public void onClick(View view) {

    switch(view.getId()){
        case R.id.btnPost:
            if(!validate())
                Toast.makeText(getBaseContext(), "Enter some data!", Toast.LENGTH_LONG).show();
            // call AsynTask to perform network operation on separate thread
            new HttpAsyncTask().execute("http://hmkcode.appspot.com/jsonservlet");
        break;
    }

}
private class HttpAsyncTask extends AsyncTask<String, Void, String> {
    @Override
    protected String doInBackground(String... urls) {

        person = new Person();
        person.setName(etName.getText().toString());
        person.setCountry(etCountry.getText().toString());
        person.setTwitter(etTwitter.getText().toString());

        return POST(urls[0],person);
    }
    // onPostExecute displays the results of the AsyncTask.
    @Override
    protected void onPostExecute(String result) {
        Toast.makeText(getBaseContext(), "Data Sent!", Toast.LENGTH_LONG).show();
   }
}

private boolean validate(){
    if(etName.getText().toString().trim().equals(""))
        return false;
    else if(etCountry.getText().toString().trim().equals(""))
        return false;
    else if(etTwitter.getText().toString().trim().equals(""))
        return false;
    else
        return true;    
}
private static String convertInputStreamToString(InputStream inputStream) throws IOException{
    BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(inputStream));
    String line = "";
    String result = "";
    while((line = bufferedReader.readLine()) != null)
        result += line;

    inputStream.close();
    return result;

}   
}

In the catch block of POST() add a line 在POST()的catch块中添加一行

result="Exception: " + e.getMessage(); 

Then in onPostExecute 然后在onPostExecute

Toast (....,result,...);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在哪里上传图片/文件以使其显示在HTML上? - Where to upload an image/file to make it appear on HTML? 按钮不在应有的位置 - Button not where supposed to be 将html的内容发布到REST api,并从Web服务获取响应 - POST contents of a html to REST api ,and GET response from the webservice 使用JAVAEE在Debugger中显示POST响应HTML页面,但在浏览器中不显示 - POST response HTML page showed in Debugger but not in Browser using JAVAEE 通过BlackBerry发送POST数据后获取HTML响应 - Get HTML response after sending POST data via BlackBerry 如何在另一个HTML页面中获取相同的xhr发布响应数据? - How to get the same xhr post response data in another html page? Java Applet布局未出现,因为它应为o_O - Java Applet Layout Doesn't Appear As It Is Supposed To o_O Java中的isReachable看起来并没有像预期的那样工作 - isReachable in Java doesn't appear to be working quite the way it's supposed to 初始屏幕后,应用程序崩溃(应显示菜单屏幕时) - The application crashes after the splash screen (When the menu screen supposed to appear) 如何通过 java 代码在响应不是 200 的调用后捕获错误响应正文和错误代码? - How to capture error response body and error code in post call where the response is not 200 via java code?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM