簡體   English   中英

android HTTP POST錯誤

[英]android HTTP POST error

好的,所以我在新類中創建了一個方法,並從try catch塊的活動中調用了該方法,當我調用它並傳遞我的字符串值時,我的問題就出現了……

執行以下方法后,我的問題開始了:

HttpResponse httpresponse = httpclient.execute(httppostreq);

它進入了我的活動的捕獲范圍(IOException e),當我嘗試打印響應字符串時,它給了我來自服務器的響應!

所以問題是當我嘗試將值傳遞給POST時,它應該返回一些數據,但是失敗了,並且正在從服務器返回空消息

提示:如果沒有值,將顯示空消息

jsonobj.put("screenType", requestString);

那么我是否通過了價值? 以及為什么會引起異常?

public void postData(String requestString) throws JSONException, ClientProtocolException, IOException {

    // Create a new HttpClient and Post Header
    DefaultHttpClient httpclient = new DefaultHttpClient();
    JSONObject jsonobj = new JSONObject();
    jsonobj.put("screenType", requestString);
    //jsonobj.put("old_passw", "306");
    HttpPost httppostreq = new HttpPost("mysite.org");
    StringEntity se = new StringEntity(jsonobj.toString());
    se.setContentType("application/json;charset=UTF-8");
    se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,"application/json;charset=UTF-8"));
    httppostreq.setEntity(se);
    HttpResponse httpresponse = httpclient.execute(httppostreq);

    Log.i("in try", httpresponse.toString());
    String responseText=null;

    try {

        responseText=EntityUtils.toString(httpresponse.getEntity());
    } catch (Exception e) {

        // TODO: handle exception
        e.printStackTrace();
        Log.i("in Exception",e.toString());
        Log.i("arse exception", httpresponse.toString());
    }
} 

我還添加了互聯網許可

<uses-permission android:name="android.permission.INTERNET" />

您不能在主線程上發出網絡請求。 您會收到現在看到的錯誤。 您需要使用AsyncTask或創建一個新線程。 就個人而言,我將使用AsyncTask。 使用AsyncTask時,可以使用onPostExecute方法將值返回到主線程。

請參閱: NetworkOnMainThreadException

正如文森特(Vincent)所說,您無法在UI線程中執行網絡請求,它將給您一個怪異的異常,但與其使用AsyncTask(如果您的活動如該信息圖表所示旋轉,該AsyncTask會被破壞),我建議您使用Robospice我使用過的最好的網絡框架,它很容易使用,祝您好運。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM