-1

Java で次のコードを記述して、POST 変数を介して Web サイトの PHP ファイルにデータを送信した後、この Web サイトのソース コードを取得したいと考えています。

public DatabaseRequest(String url, IDatabaseCallback db_cb)
        {
            this.db_cb = db_cb;
            site_url = url;
            client = new DefaultHttpClient();
            request = new HttpPost(site_url);
            responseHandler = new BasicResponseHandler();
            nameValuePairs = new ArrayList<NameValuePair>(0);
        }

        public void addParameter(List<NameValuePair> newNameValuePairs)
        {
            nameValuePairs = newNameValuePairs;
        }

        public void run()
        {
            db_cb.databaseFinish(getContent());
        }

        public String[] getContent()
        {

            String result = "";
            try {
                request.setEntity(new UrlEncodedFormEntity(nameValuePairs));  
                result = client.execute(request, responseHandler);
            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            String[] result_arr = result.trim().split("<br>");
            for (int i = 0; i < result_arr.length; i++)
            {
                result_arr[i] = result_arr[i].trim();
            }
            return result_arr;
        }

このコードを実行したい場合、Eclipse は次のエラー メッセージをスローします。 エラーメッセージ

4

1 に答える 1

1

これを試して:

// executes the request and gets the response.
HttpResponse response = client.execute(httpPostRequest);
// get the status code--- 200 = Http.OK
int statusCode = response.getStatusLine().getStatusCode();

HttpEntity httpEntity = response.getEntity();
responseBody = httpEntity.getContent();    

if (statusCode = 200) {
    // process the responseBody. 
}
else{
    // there is some error in responsebody
}

編集:処理するにはUnsupportedEncodingException

HTTP リクエストを行う前に、すべての文字列データを有効な URL 形式に変換するために、投稿データをエンコードする必要があります。

// Url Encoding the POST parameters
try {
    httpPostRequest.setEntity(new UrlEncodedFormEntity(nameValuePair));
}
catch (UnsupportedEncodingException e) {
    // writing error to Log
    e.printStackTrace();
}
于 2013-08-20T19:45:13.200 に答える